jQuery에서 요소 "플래시"를 만드는 방법
저는 jQuery에 새로 와서 프로토타입을 사용해 본 경험이 있습니다.프로토타입에는 요소를 "플래시"하는 방법이 있습니다. 즉, 다른 색상으로 간단히 강조 표시한 후 사용자의 시선이 해당 요소에 쏠릴 수 있도록 원래대로 페이드백합니다.jQuery에 그런 방법이 있습니까?페이드인, 페이드아웃, 애니메이션은 표시되지만 "플래시"와 같은 것은 표시되지 않습니다.이 세 가지 중 하나를 적절한 입력과 함께 사용할 수 있습니까?
제 방식은 .fadein, .fadeout, .fadeout입니다.
$("#someElement").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
function go1() { $("#demo1").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)}
function go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') }
#demo1,
#demo2 {
text-align: center;
font-family: Helvetica;
background: IndianRed;
height: 50px;
line-height: 50px;
width: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="go1()">Click Me</button>
<div id='demo1'>My Element</div>
<br>
<button onclick="go2()">Click Me</button> (from comment)
<div id='demo2'>My Element</div>
jQuery Color 플러그인을 사용할 수 있습니다.
예를 들어, 페이지의 모든 div에 주의를 기울이려면 다음 코드를 사용할 수 있습니다.
$("div").stop().css("background-color", "#FFFF9C")
.animate({ backgroundColor: "#FFFFFF"}, 1500);
편집 - 새 기능 및 향상된 기능
다음은 위와 동일한 기술을 사용하지만 다음과 같은 추가 이점이 있습니다.
- 매개 변수화된 강조 색상 및 기간
- 흰색으로 가정하는 대신 원래 배경색 유지
- jQuery의 확장이므로 모든 개체에 사용할 수 있습니다.
jQuery 개체 확장:
var notLocked = true;
$.fn.animateHighlight = function(highlightColor, duration) {
var highlightBg = highlightColor || "#FFFF9C";
var animateMs = duration || 1500;
var originalBg = this.css("backgroundColor");
if (notLocked) {
notLocked = false;
this.stop().css("background-color", highlightBg)
.animate({backgroundColor: originalBg}, animateMs);
setTimeout( function() { notLocked = true; }, animateMs);
}
};
사용 예:
$("div").animateHighlight("#dd0000", 1000);
CSS3 애니메이션을 사용하여 요소를 플래시할 수 있습니다.
.flash {
-moz-animation: flash 1s ease-out;
-moz-animation-iteration-count: 1;
-webkit-animation: flash 1s ease-out;
-webkit-animation-iteration-count: 1;
-ms-animation: flash 1s ease-out;
-ms-animation-iteration-count: 1;
}
@keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
@-webkit-keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
@-moz-keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
@-ms-keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
그리고 당신은 클래스를 추가하기 위해 jQuery를 합니다.
jQuery(selector).addClass("flash");
5년 후에...(추가 플러그인 필요 없음)
이 장치는 뒤에 div 배경색을 넣은 다음 개체를 다시 페이드아웃하여 원하는 색상(예: 흰색)으로 "펄스"합니다.
HTML 개체(예: 버튼):
<div style="background: #fff;">
<input type="submit" class="element" value="Whatever" />
</div>
jQuery(vanilla, 다른 플러그인 없음):
$('.element').fadeTo(100, 0.3, function() { $(this).fadeTo(500, 1.0); });
요소 - 클래스 이름
의 제1인자.fadeTo()
)
에서 두 번째 번호.fadeTo()
페이드 후
이 웹 페이지의 오른쪽 하단 모서리에서 확인할 수 있습니다. https://single.majlovesreg.one/v1/
$(이)와 조정된 값을 사용하여 중복된 선택기를 편집(강조)하여 실제로 플래시를 수행합니다(OP 요청대로).
당신은 jQuery UI에서 하이라이트 효과를 사용하여 동일한 결과를 얻을 수 있다고 생각합니다.
UI를 jQuery UI가 있습니다.pulsate
에서 합니다.UI/Effects
$("div").click(function () {
$(this).effect("pulsate", { times:3 }, 2000);
});
http://docs.jquery.com/UI/Effects/Pulsate
$('#district').css({opacity: 0});
$('#district').animate({opacity: 1}, 700 );
순수 jQuery 솔루션입니다.
(jquery-ui/애니메이션/색상 필요 없음)
jquery 색상을 로드하지 않고 노란색 "플래시" 효과만 원하는 경우:
var flash = function(elements) {
var opacity = 100;
var color = "255, 255, 20" // has to be in this format since we use rgba
var interval = setInterval(function() {
opacity -= 3;
if (opacity <= 0) clearInterval(interval);
$(elements).css({background: "rgba("+color+", "+opacity/100+")"});
}, 30)
};
위의 스크립트는 단순히 1s 노란색 페이드아웃을 수행하며, 사용자에게 요소가 업데이트되었거나 유사한 것이 있음을 알리기에 완벽합니다.
용도:
flash($('#your-element'))
이 플러그인을 사용할 수 있습니다(js 파일에 넣고 스크립트 태그를 통해 사용).
http://plugins.jquery.com/project/color
그런 다음 다음 다음과 같은 것을 사용합니다.
jQuery.fn.flash = function( color, duration )
{
var current = this.css( 'color' );
this.animate( { color: 'rgb(' + color + ')' }, duration / 2 );
this.animate( { color: current }, duration / 2 );
}
그러면 모든 jQuery 개체에 'flash' 메서드가 추가됩니다.
$( '#importantElement' ).flash( '255,0,0', 1000 );
반복 횟수가 다음과 같이 여러 번 깜박이도록 허용하면 Desheng Li 방법을 더욱 확장할 수 있습니다.
// Extend jquery with flashing for elements
$.fn.flash = function(duration, iterations) {
duration = duration || 1000; // Default to 1 second
iterations = iterations || 1; // Default to 1 iteration
var iterationDuration = Math.floor(duration / iterations);
for (var i = 0; i < iterations; i++) {
this.fadeOut(iterationDuration).fadeIn(iterationDuration);
}
return this;
}
그런 다음 시간과 깜박이는 횟수를 사용하여 메소드를 호출할 수 있습니다.
$("#someElementId").flash(1000, 4); // Flash 4 times over a period of 1 second
정말 간단한 대답은 어떻습니까?
$('selector').fadeTo('fast',0).fadeTo('fast',1).fadeTo('fast',0).fadeTo('fast',1)
두 번 깜박임...이상입니다, 여러분!
아직 이 문제에 관한 것이 아니라는 것을 믿을 수 없습니다.당신이 해야 할 일은:
("#someElement").show('highlight',{color: '#C8FB5E'},'fast');
하고, , 이은정확당하고것, 우쉽고효있다습니모, 가과에두두가지것히을이신는하매원 모두에 .show()
그리고.hide()
방법들.
이것은 좀 더 최신의 답변일 수 있으며, 이 게시물 이후 상황이 다소 통합되었기 때문에 더 짧습니다.jquery-ui-effect-highlight가 필요합니다.
$("div").click(function () {
$(this).effect("highlight", {}, 3000);
});
http://docs.jquery.com/UI/Effects/Highlight
function pulse() {
$('.blink').fadeIn(300).fadeOut(500);
}
setInterval(pulse, 1000);
저는 jQuery UI에 의존하지 않고 이 문제에 대한 해결책을 찾고 있었습니다.
이것이 제가 생각해낸 것이고 저에게 효과가 있습니다(플러그인은 없고 자바스크립트와 jQuery만 있음); -- 여기 작업용 바이올린입니다 -- http://jsfiddle.net/CriddleCraddle/yYcaY/2/
CSS 파일에서 현재 CSS 매개 변수를 일반 CSS로 설정하고, background-color와 같이 변경할 매개 변수만 처리하는 새 클래스를 만들고, 기본 동작을 재정의하려면 '!important'로 설정합니다.이렇게...
.button_flash {
background-color: #8DABFF !important;
}//This is the color to change to.
그런 다음 아래 기능을 사용하여 DOM 요소를 문자열로 전달하고, 플래시가 발생할 횟수에 대한 정수, 변경할 클래스에 대한 정수 및 지연에 대한 정수로 전달합니다.
참고: 'times' 변수에 짝수를 전달하면 시작한 클래스가 되고, 홀수를 전달하면 토글된 클래스가 됩니다.둘 다 다른 일에 유용합니다.저는 지연 시간을 변경하기 위해 'i'를 사용합니다. 그렇지 않으면 모두 동시에 작동하여 효과가 사라집니다.
function flashIt(element, times, klass, delay){
for (var i=0; i < times; i++){
setTimeout(function(){
$(element).toggleClass(klass);
}, delay + (300 * i));
};
};
//Then run the following code with either another delay to delay the original start, or
// without another delay. I have provided both options below.
//without a start delay just call
flashIt('.info_status button', 10, 'button_flash', 500)
//with a start delay just call
setTimeout(function(){
flashIt('.info_status button', 10, 'button_flash', 500)
}, 4700);
// Just change the 4700 above to your liking for the start delay. In this case,
//I need about five seconds before the flash started.
펄스 효과(오프라인) JQuery 플러그인이 찾고 있는 것에 적합합니까?
펄스 효과를 제한하는 시간을 추가할 수 있습니다.
J-P가 댓글에서 언급했듯이, 현재 그의 업데이트된 펄스 플러그인이 있습니다.
그의 깃허브 레포를 보세요.그리고 여기 데모가 있습니다.
나중에 이렇게 많은 달을 찾았지만, 관심 있는 사람이 있다면, 이것은 무언가를 영구적으로 깜박이게 하는 좋은 방법인 것 같습니다.
$( "#someDiv" ).hide();
setInterval(function(){
$( "#someDiv" ).fadeIn(1000).fadeOut(1000);
},0)
다음 코드가 저에게 적합합니다.두 개의 페이드인 및 페이드아웃 기능을 정의하고 서로의 콜백에 넣습니다.
var fIn = function() { $(this).fadeIn(300, fOut); };
var fOut = function() { $(this).fadeOut(300, fIn); };
$('#element').fadeOut(300, fIn);
다음은 깜박임 시간을 제어합니다.
var count = 3;
var fIn = function() { $(this).fadeIn(300, fOut); };
var fOut = function() { if (--count > 0) $(this).fadeOut(300, fIn); };
$('#element').fadeOut(300, fIn);
라이브러리를 포함하는 것이 과도한 작업인 경우 여기에 사용할 수 있는 해결책이 있습니다.
$('div').click(function() {
$(this).css('background-color','#FFFFCC');
setTimeout(function() { $(this).fadeOut('slow').fadeIn('slow'); } , 1000);
setTimeout(function() { $(this).css('background-color','#FFFFFF'); } , 1000);
});
이벤트 트리거 설정
블록 요소의 배경색 설정
Inside setTimeout은 fadeOut과 fadeIn을 사용하여 약간의 애니메이션 효과를 만듭니다.
내부 second setTimeout 재설정 기본 배경색
몇 개의 브라우저에서 테스트되었으며 잘 작동합니다.
페이드인/페이드아웃처럼 애니메이션 CSS/지연을 사용할 수 있습니다.
$(this).stop(true, true).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100);
단순하고 유연함
$("#someElement").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1);
3000은 3초입니다.
불투명도 1에서 0.3으로 색이 바랜 다음 1로 색이 바랜다.
이것들을 더 쌓을 수 있습니다.
jQuery만 필요합니다.:)
애니메이션 배경 버그에 대한 해결 방법이 있습니다.이 요지에는 간단한 강조 표시 방법과 그 사용의 예가 포함되어 있습니다.
/* BEGIN jquery color */
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(!fx.colorInit){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);fx.colorInit=true;}
fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)
return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];if(result=/rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent'];return colors[jQuery.trim(color).toLowerCase()];}
function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))
break;attr="backgroundColor";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};})(jQuery);
/* END jquery color */
/* BEGIN highlight */
jQuery(function() {
$.fn.highlight = function(options) {
options = (options) ? options : {start_color:"#ff0",end_color:"#fff",delay:1500};
$(this).each(function() {
$(this).stop().css({"background-color":options.start_color}).animate({"background-color":options.end_color},options.delay);
});
}
});
/* END highlight */
/* BEGIN highlight example */
$(".some-elements").highlight();
/* END highlight example */
https://gist.github.com/1068231
안타깝게도 상위 답변에는 JQuery UI가 필요합니다. http://api.jquery.com/animate/
바닐라 제이쿼리 솔루션입니다.
제이에스
var flash = "<div class='flash'></div>";
$(".hello").prepend(flash);
$('.flash').show().fadeOut('slow');
CSS
.flash {
background-color: yellow;
display: none;
position: absolute;
width: 100%;
height: 100%;
}
HTML
<div class="hello">Hello World!</div>
콜비어헤이의 솔루션을 약간 개선한 버전이 있습니다.저는 애니메이션을 호출한 후 실제 jQuery 형태로 이벤트를 체인화하도록 반환문을 추가했습니다.또한 대기열을 지우고 애니메이션의 끝으로 이동하기 위한 인수를 추가했습니다.
// Adds a highlight effect
$.fn.animateHighlight = function(highlightColor, duration) {
var highlightBg = highlightColor || "#FFFF9C";
var animateMs = duration || 1500;
this.stop(true,true);
var originalBg = this.css("backgroundColor");
return this.css("background-color", highlightBg).animate({backgroundColor: originalBg}, animateMs);
};
마우스 오버 이벤트가 트리거될 때까지 요소의 배경색을 펄스화합니다.
$.fn.pulseNotify = function(color, duration) {
var This = $(this);
console.log(This);
var pulseColor = color || "#337";
var pulseTime = duration || 3000;
var origBg = This.css("background-color");
var stop = false;
This.bind('mouseover.flashPulse', function() {
stop = true;
This.stop();
This.unbind('mouseover.flashPulse');
This.css('background-color', origBg);
})
function loop() {
console.log(This);
if( !stop ) {
This.animate({backgroundColor: pulseColor}, pulseTime/3, function(){
This.animate({backgroundColor: origBg}, (pulseTime/3)*2, 'easeInCirc', loop);
});
}
}
loop();
return This;
}
위의 모든 것을 조합하면 요소를 깜박이고 원래 bg 색상으로 돌아갈 수 있는 쉬운 솔루션이 됩니다.
$.fn.flash = function (highlightColor, duration, iterations) {
var highlightBg = highlightColor || "#FFFF9C";
var animateMs = duration || 1500;
var originalBg = this.css('backgroundColor');
var flashString = 'this';
for (var i = 0; i < iterations; i++) {
flashString = flashString + '.animate({ backgroundColor: highlightBg }, animateMs).animate({ backgroundColor: originalBg }, animateMs)';
}
eval(flashString);
}
다음과 같이 사용:
$('<some element>').flash('#ffffc0', 1000, 3);
이것이 도움이 되길 바랍니다!
여기 jQuery와 CSS3 애니메이션을 혼합하여 사용하는 솔루션이 있습니다.
http://jsfiddle.net/padfv0u9/2/
기본적으로 색상을 "플래시" 색상으로 변경하는 것으로 시작한 다음 CSS3 애니메이션을 사용하여 색상이 희미해지도록 합니다.초기 "플래시"가 페이드보다 빠르기 위해서는 전환 기간을 변경해야 합니다.
$(element).removeClass("transition-duration-medium");
$(element).addClass("transition-duration-instant");
$(element).addClass("ko-flash");
setTimeout(function () {
$(element).removeClass("transition-duration-instant");
$(element).addClass("transition-duration-medium");
$(element).removeClass("ko-flash");
}, 500);
여기서 CSS 클래스는 다음과 같습니다.
.ko-flash {
background-color: yellow;
}
.transition-duration-instant {
-webkit-transition-duration: 0s;
-moz-transition-duration: 0s;
-o-transition-duration: 0s;
transition-duration: 0s;
}
.transition-duration-medium {
-webkit-transition-duration: 1s;
-moz-transition-duration: 1s;
-o-transition-duration: 1s;
transition-duration: 1s;
}
그냥 em.fadeOut(10).fadeIn(10);
이것은 애니메이션을 만들 코드를 작성할 수 있을 정도로 충분히 일반적입니다.지연 시간을 300ms에서 33ms로 줄이고 색상을 페이드할 수도 있습니다.
// Flash linked to hash.
var hash = location.hash.substr(1);
if (hash) {
hash = $("#" + hash);
var color = hash.css("color"), count = 1;
function hashFade () {
if (++count < 7) setTimeout(hashFade, 300);
hash.css("color", count % 2 ? color : "red");
}
hashFade();
}
jquery Pulsate 플러그인을 사용하여 속도, 반복 및 색상을 제어하는 HTML 요소에 주의를 집중시킬 수 있습니다.
JQuery.pulsate() 데모 포함
샘플 이니셜라이저:
- $(".sv4").펄스 속도(속도:2500})
- $(."CommandBox 버튼:표시됨").맥동수({색상: "#f00", 속도: 200, 도달: 85, 반복: 15 }
언급URL : https://stackoverflow.com/questions/275931/how-do-you-make-an-element-flash-in-jquery
'programing' 카테고리의 다른 글
SQL Server 2005의 날짜/시간에서 월 및 연도 가져오기 (0) | 2023.05.11 |
---|---|
Bash를 사용하여 절대 경로를 현재 디렉터리가 지정된 상대 경로로 변환 (0) | 2023.05.11 |
시스템 앱에만 권한이 부여됩니다. (0) | 2023.05.11 |
mongodb에서 aggregate를 $match_id로 사용하는 방법 (0) | 2023.05.11 |
TorothyGit 사용자 인증/자격 증명 저장 (0) | 2023.05.11 |