programing

JQuery를 통한 노란색 페이드 효과

minimums 2023. 8. 16. 22:06
반응형

JQuery를 통한 노란색 페이드 효과

저는 37Signals의 Yellow Fade 효과와 유사한 것을 구현하고 싶습니다.

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

코드

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

다음 통화에서는 상자 ID로 DOMEment를 노란색으로 페이드합니다.

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

하지만 그것은 그것을 노란색으로 만들 뿐입니다.15000밀리초 후에는 흰색 배경이 없습니다.

왜 안 되는지 아세요?

해결책

사용할 수 있는 항목:

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

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

효과.core.js
영향들.하이라이트.js

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

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

Steerpike가 코멘트에서 지적했듯이, effects.core.js effects.이를 사용하려면 highlight.js를 포함해야 합니다.

저는 스털링 니콜스의 답변이 가벼웠고 플러그인이 필요하지 않았기 때문에 좋았습니다.그러나 부동 요소(예: 요소가 "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(); });
    });
}

jQuery effects 라이브러리는 앱에 불필요한 오버헤드를 상당히 추가합니다.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();

다음과 같이 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/

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

요령을 터득해야 합니다.노란색으로 설정한 다음 흰색으로 페이드합니다.

제가 진행하던 프로젝트에서 이와 유사한 문제를 방금 해결했습니다.기본적으로 애니메이션 기능은 색상을 애니메이션으로 만들 수 없습니다.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와 함께 작동하도록 변경했습니다.

NB: 파이어폭스 3 및 iE 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('#myDivId');

신용: Phil Haack은 이것을 어떻게 하는지를 보여주는 데모를 했습니다.그는 JQuery와 ASPNet MVC에서 데모를 하고 있었습니다.

이 비디오를 보세요.

업데이트: 비디오를 보셨습니까?JQuery가 필요하다는 것을 언급하는 것을 잊었습니다.컬러 플러그인

저는 effects.core.js와 effects를 추가하기 위해 23kb를 추가하는 것이 싫었습니다.highlight.js 그래서 다음과 같이 썼습니다.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')로 호출합니다.페더 효과();

이것이 그 문제에 대한 나의 해결책입니다.그것은 아주 잘 작동합니다.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> 

난 그냥...

<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>

HTML만 있으면 됩니다.CSS 또는 JS가 필요하지 않습니다!

특정 페이지에 페이지를 방문할 때 사용자에게 일시적으로 "강조하여 표시"하려는 텍스트가 있다고 가정합니다.

그리고 아래와 같이 해당 페이지의 콘텐츠를 h2 태그 및 앱 태그 콘텐츠로 강조합니다.


<h2>Carbon Steel for Blacksmithing</h2>

<p>The vast majority of blacksmithing uses low and medium carbon steels. High carbon steel, sometimes called “carbon tool steel,” is very hard, and difficult to bend or weld; it gets very brittle once it’s been heat-treated.</p>
<p>You can buy steel, or you can find and recycle. I prefer the later.</p>

아래에 제공된 링크는 위에 표시된 내용을 실제로 강조 표시합니다.사용자가 이 링크를 클릭할 때마다...내용이 있는 동일한 위치로 페이지로 리디렉션되고 텍스트도 강조 표시됩니다!

https://stackoverflow.com/questions/848797/yellow-fade-effect-with-jquery/63571443#:~:text=Carbon%20Steel%20for%20Blacksmithing,you%20can%20find%20and%20recycle.

실시간 예를 들어보겠습니다.위의 링크를 따라가면 링크에서 언급한 내용에 대한 하이라이트 효과를 확인할 수 있습니다.

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>

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

<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

반응형