Programming

JQuery를 사용한 노란색 페이드 효과

procodes 2020. 8. 22. 12:33
반응형

JQuery를 사용한 노란색 페이드 효과


37Signals의 Yellow Fade 효과 와 비슷한 것을 구현하고 싶습니다 .

Jquery 1.3.2를 사용하고 있습니다.

코드

(function($) {
   $.fn.yellowFade = function() {
    return (this.css({backgroundColor: "#ffffcc"}).animate(
            {
                backgroundColor: "#ffffff"
            }, 1500));
   }
 })(jQuery);

다음 호출은 상자 ID로 DOM 요소를 노란색 페이드로 표시 합니다.

$("#box").yellowFade();

그러나 그것은 단지 그것을 노란색으로 만듭니다. 15000 밀리 초 후에 흰색 배경이 없습니다.

왜 작동하지 않는지 아십니까?

해결책

당신이 사용할 수있는:

$("#box").effect("highlight", {}, 1500);

그러나 다음을 포함해야합니다.

effects.core.js
effects.highlight.js


이 함수는 jQuery effects.core.js의 일부입니다 .

$("#box").effect("highlight", {}, 1500);

Steerpike가 주석에서 지적했듯이이 기능 을 사용하려면 effects.core.jseffects.highlight.js 가 포함되어야합니다.


jQuery 효과 라이브러리는 앱에 불필요한 오버 헤드를 상당히 추가합니다. jQuery로만 동일한 작업을 수행 할 수 있습니다. http://jsfiddle.net/x2jrU/92/

jQuery.fn.highlight = function() {
   $(this).each(function() {
        var el = $(this);
        el.before("<div/>")
        el.prev()
            .width(el.width())
            .height(el.height())
            .css({
                "position": "absolute",
                "background-color": "#ffff99",
                "opacity": ".9"   
            })
            .fadeOut(500);
    });
}

$("#target").highlight();

가볍고 플러그인이 필요하지 않았기 때문에 Sterling Nichols 답변을 좋아했습니다. 그러나 플로팅 요소 (예 : 요소가 "float : right"인 경우)에서는 작동하지 않음을 발견했습니다. 따라서 요소가 페이지에 어떻게 배치 되든 상관없이 강조 표시를 올바르게 표시하도록 코드를 다시 작성했습니다.

jQuery.fn.highlight = function () {
    $(this).each(function () {
        var el = $(this);
        $("<div/>")
        .width(el.outerWidth())
        .height(el.outerHeight())
        .css({
            "position": "absolute",
            "left": el.offset().left,
            "top": el.offset().top,
            "background-color": "#ffff99",
            "opacity": ".7",
            "z-index": "9999999"
        }).appendTo('body').fadeOut(1000).queue(function () { $(this).remove(); });
    });
}

선택 사항 :
요소의 테두리 반경도 일치 시키려면 다음 코드를 사용하세요.

jQuery.fn.highlight = function () {
    $(this).each(function () {
        var el = $(this);
        $("<div/>")
        .width(el.outerWidth())
        .height(el.outerHeight())
        .css({
            "position": "absolute",
            "left": el.offset().left,
            "top": el.offset().top,
            "background-color": "#ffff99",
            "opacity": ".7",
            "z-index": "9999999",
            "border-top-left-radius": parseInt(el.css("borderTopLeftRadius"), 10),
            "border-top-right-radius": parseInt(el.css("borderTopRightRadius"), 10),
            "border-bottom-left-radius": parseInt(el.css("borderBottomLeftRadius"), 10),
            "border-bottom-right-radius": parseInt(el.css("borderBottomRightRadius"), 10)
        }).appendTo('body').fadeOut(1000).queue(function () { $(this).remove(); });
    });
}

(function($) {
  $.fn.yellowFade = function() {
    this.animate( { backgroundColor: "#ffffcc" }, 1 ).animate( { backgroundColor: "#ffffff" }, 1500 );
  }
})(jQuery);

트릭을해야합니다. 노란색으로 설정 한 다음 흰색으로 페이드


다음과 같이 CSS를 정의하십시오.

@-webkit-keyframes yellowfade {
    from { background: yellow; }
    to { background: transparent; }
}

@-moz-keyframes yellowfade {
    from { background: yellow; }
    to { background: transparent; }
}

.yft {
    -webkit-animation: yellowfade 1.5s;
       -moz-animation: yellowfade 1.5s;
            animation: yellowfade 1.5s;
}

yft모든 항목에 클래스 추가하기 만하면$('.some-item').addClass('yft')

데모 : http://jsfiddle.net/Q8KVC/528/


작업중인 프로젝트에서 이와 유사한 문제를 방금 해결했습니다. 기본적으로 애니메이션 기능은 색상에 애니메이션을 적용 할 수 없습니다. jQuery Color Animations를 포함 해보십시오 .

여기의 모든 답변은이 플러그인을 사용하지만 아무도 언급하지 않습니다.


실제로 jQuery 1.3x 만 필요하고 추가 플러그인이없는 솔루션이 있습니다.

먼저 스크립트에 다음 함수를 추가하십시오.

function easeInOut(minValue,maxValue,totalSteps,actualStep,powr) {
    var delta = maxValue - minValue;
    var stepp = minValue+(Math.pow(((1 / totalSteps)*actualStep),powr)*delta);
    return Math.ceil(stepp)
}

function doBGFade(elem,startRGB,endRGB,finalColor,steps,intervals,powr) {
    if (elem.bgFadeInt) window.clearInterval(elem.bgFadeInt);
    var actStep = 0;
    elem.bgFadeInt = window.setInterval(
        function() {
            elem.css("backgroundColor", "rgb("+
                easeInOut(startRGB[0],endRGB[0],steps,actStep,powr)+","+
                easeInOut(startRGB[1],endRGB[1],steps,actStep,powr)+","+
                easeInOut(startRGB[2],endRGB[2],steps,actStep,powr)+")"
            );
            actStep++;
            if (actStep > steps) {
            elem.css("backgroundColor", finalColor);
            window.clearInterval(elem.bgFadeInt);
            }
        }
        ,intervals)
}

다음으로 다음을 사용하여 함수를 호출합니다.

doBGFade( $(selector),[245,255,159],[255,255,255],'transparent',75,20,4 );

매개 변수를 추측 해 보겠습니다.이 매개 변수는 자명합니다. 솔직히 말해서 스크립트는 나에게서 온 것이 아니기 때문에 페이지에서 가져온 다음 최신 jQuery에서 작동하도록 변경했습니다.

주의 : 파이어 폭스 3 및 6에서 테스트되었습니다 (예, 이전 버전에서도 작동합니다).


function YellowFade(selector){
   $(selector)
      .css('opacity', 0)
      .animate({ backgroundColor: 'Yellow', opacity: 1.0 }, 1000)
      .animate({ backgroundColor: '#ffffff', opacity: 0.0}, 350, function() {
             this.style.removeAttribute('filter');
              });
}

이 줄 this.style.removeAttribute('filter')은 IE의 앤티 앨리어싱 버그입니다.

이제 어디에서나 YellowFade를 호출하고 선택기를 전달하십시오.

YellowFade('#myDivId');

신용 : Phil Haack은이를 수행하는 방법을 정확히 보여주는 데모를 가지고있었습니다. 그는 JQuery와 ASPNet MVC에 대한 데모를하고있었습니다.

이 비디오를보세요

업데이트 : 영상 보셨나요? 이것을 언급하는 것을 잊었을JQuery.Color 플러그인 이 필요합니다.


effects.core.js 및 effects.highlight.js를 추가하기 위해 23kb를 추가하는 것이 싫었으므로 다음을 작성했습니다. 요소를 '플래시'하기 위해 fadeIn (jQuery 자체의 일부)을 사용하여 동작을 에뮬레이트합니다.

$.fn.faderEffect = function(options){
    options = jQuery.extend({
        count: 3, // how many times to fadein
        speed: 500, // spped of fadein
        callback: false // call when done
    }, options);

    return this.each(function(){

        // if we're done, do the callback
        if (0 == options.count) 
        {
            if ( $.isFunction(options.callback) ) options.callback.call(this);
            return;
        }

        // hide so we can fade in
        if ( $(this).is(':visible') ) $(this).hide();

        // fade in, and call again
        $(this).fadeIn(options.speed, function(){
            options.count = options.count - 1; // countdown
            $(this).faderEffect(options); 
        });
    });
}

그런 다음 $ ( '. item'). faderEffect ();


이것이 문제에 대한 나의 해결책입니다. 그것은 훌륭하게 작동합니다. jslint 오류 유효성 검사를 통과하고 IE8 및 IE9에서도 제대로 작동합니다. 물론 색상 코드와 콜백을 받도록 조정할 수 있습니다.

jQuery.fn.highlight = function(level) {

  highlightIn = function(options){

    var el = options.el;
    var visible = options.visible !== undefined ? options.visible : true;

    setTimeout(function(){
      if (visible) {
        el.css('background-color', 'rgba('+[255, 64, 64]+','+options.iteration/10+')');
        if (options.iteration/10 < 1) {
          options.iteration += 2;
          highlightIn(options);
        }
      } else {
        el.css('background-color', 'rgba('+[255, 64, 64]+','+options.iteration/10+')');
        if (options.iteration/10 > 0) {
          options.iteration -= 2;
          highlightIn(options);
        } else {
          el.css('background-color', '#fff');
        }
      }
    }, 50);
  };

  highlightOut = function(options) {
    options.visible = false;
    highlightIn(options);
  };

  level = typeof level !== 'undefined' ? level : 'warning';
  highlightIn({'iteration': 1, 'el': $(this), 'color': level});
  highlightOut({'iteration': 10, 'el': $(this), 'color': level});
};

색상 페이드 효과에 사용할 수있는 비 jQuery 옵션입니다. "colors"배열에서 초기 색상에서 마지막 색상까지 필요한 전환 색상을 추가합니다. 원하는만큼 색상을 추가 할 수 있습니다.

   <html lang="en">
   <head>
   <script type="text/javascript">
  //###Face Effect for a text box#######

var targetColor;
var interval1;
var interval2;
var i=0;
var colors = ["#FFFF00","#FFFF33","#FFFF66","#FFFF99","#FFFFCC","#FFFFFF"];

function changeColor(){
    if (i<colors.length){
        document.getElementById("p1").style.backgroundColor=colors[i];
        i++;
    } 
    else{
        window.clearInterval(interval1);
        i=0;
    }
}
addEventListener("load",function(){
    document.getElementById("p1").addEventListener("click",function(e){
        interval1=setInterval("changeColor()",80);              

    })
});
</script>

</head>

<body>
<p id="p1">Click this text box to see the fade effect</p>

<footer>
 <p>By Jefrey Bulla</p>
</footer>
</div>
</body>
</html> 

jQuery UI .effect에 의존하지 않는 대체 노란색 페이드 기술을 시도하려면 콘텐츠 뒤에 노란색 (또는 다른 색상) div를 배치하고 jQuery .fadeOut ()을 사용할 수 있습니다.

http://jsfiddle.net/yFJzn/2/

<div class="yft">
    <div class="content">This is some content</div>
    <div class="yft_fade">&nbsp;</div>
</div>

<style>
  .yft_fade {
      background-color:yellow;
      display:none;
  }
  .content {
      position:absolute;
      top:0px;
  }
</style>

<script>
  $(document).ready(function() {
      $(".yft").click(function() {
          $(this).find(".yft_fade").show().fadeOut();
      });
  });​
</script>

나는 단순히 사용 ...

<style>
tr.highlight {
background: #fffec6;
}
</style>


<script>
//on page load, add class
$(window).load(function() {
$("tr.table-item-id").addClass("highlight", 1200);
}); 

//fade out class
setTimeout(function(){
$("tr.table-item-id").removeClass("highlight", 1200);   
}, 5200);

</script>

"노란색 페이드 아웃"을위한 단순 / 원시 스크립트, jquery 자체를 제외하고 플러그인 없음 . 타이머에서 rgb (255,255, highlightcolor)로 배경 설정 :

<script>

    $(document).ready(function () {
        yellowFadeout();
    });

    function yellowFadeout() {
        if (typeof (yellowFadeout.timer) == "undefined")
            yellowFadeout.timer = setInterval(yellowFadeout, 50);
        if (typeof (yellowFadeout.highlightColor) == "undefined")
            yellowFadeout.highlightColor = 0;
        $(".highlight").css('background', 'rgb(255,255,' + yellowFadeout.highlightColor + ')');
        yellowFadeout.highlightColor += 10;
        if (yellowFadeout.highlightColor >= 255) {
            $(".highlight").css('background','');
            clearInterval(yellowFadeout.timer);
        }
    }
</script>

참고 URL : https://stackoverflow.com/questions/848797/yellow-fade-effect-with-jquery

반응형