JQuery的黄色淡入淡出效果


100

我想实现类似于37Signals的Yellow Fade效果。

我正在使用Jquery 1.3.2

代码

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

而下一个呼叫显示为黄色,则会淡化带有框号的DOM元素。

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

但这只会使它变黄。15000毫秒后没有白色背景。

知道为什么它不起作用吗?

您可以使用:

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

但是您需要包括:

effects.core.js
effects.highlight.js


Answers:


98

此函数是jQuery effects.core.js的一部分:

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

正如Steerpike在评论中指出的那样,必须包括effects.core.jseffects.highlight.js才能使用它。


1
我在jquery网站docs.jquery.com/UI/Effects/Highlight#overview中看到了该示例, 我已经在我的代码中尝试过但没有做任何事情。我是否需要下载任何其他内容。它说依赖性:Effects Core。这是另一个插件。
塞尔吉奥·阿莫

正确答案,但是我只想说它是jQuery effects.core.js的内置函数,而不是animate()的核心jQuery文件的内置函数。只是认为值得澄清。
Steerpike

5
呵呵,正如Sergio显然是刚刚发现的...是的,Sergio,您需要包括effects.core.js文件和effects.highlight.js(在此处查看源代码:docs.jquery.com/UI/Effects/Highlight
Steerpike


7
作为对先前评论的更新,您不再包括effects.core.js和effects.highlight.js(以及那些不再起作用的旧URL)。包含此内容的新方法是包括jquery-ui库:code.jquery.com/ui/1.10.4/jquery-ui.min.js
Sean Colombo

66

我喜欢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(); });
    });
}

9
我喜欢这个解决方案。在表格行上效果很好。
佩里·图

迄今为止最好的解决方案。如果它也能复制元素的边界半径,那就更好了。
Stijn Van Bael 2015年

@StijnVanBael代码现在已更新,可以复制边框半径。感谢您的建议。
Doug S

这太棒了,现在不需要我使用UI库,但是我的问题是,它在首次使用时不会突出显示整个div,可能是因为其中的一部分是空的,并且在调用此方法之前已设置了文本吗?
NaughtySquid '16

不错,但这似乎不适用于FeatherlightJs等模态。
瑞安

64

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();

4
谢谢,这更好,我一直在寻找可以避免包含完全不需要的完整UI核心的东西。
deej 2012年

你摇滚 正是我要找的东西,没有添加其他插件。而且我喜欢它确实覆盖了整个元素,而不是仅仅更改元素的背景色(可能被文本,按钮等遮盖了)。
Doug S

3
更新:尝试突出显示浮动元素时(即,当元素为“ float:right”时),此代码通常会失败。因此,无论元素在页面上的位置如何,我都重新编写了代码以正确显示突出显示的内容:stackoverflow.com/a/13106698/1145177
Doug S

感谢您的更新道格。。我将不得不更新自己的库。
Sterling Nichols

2
好的轻量级解决方案-效果很好。我发现我的突出显示虽然没有包含元素填充,所以我使用.width(el.outerWidth()).height(el.outerHeight())突出显示了整个表单字段。
Mark B

13

定义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/


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

应该做到的。将其设置为黄色,然后将其淡化为白色


感谢你的回答。它虽然没有工作。似乎动画没有任何作用。
塞尔吉奥·阿莫

您正在使用哪个版本的jQuery?

1.3.2。我将此添加到我的问题中
塞尔吉奥·阿莫

就我的目的而言,这很好用,除了香草jQuery之外没有任何依赖关系。
gojomo

3
这需要jQuery.Color()插件才能工作:github.com/jquery/jquery-color
Dia Kharrat

7

我刚刚在一个正在进行的项目中解决了与此类似的问题。默认情况下,动画功能无法为颜色设置动画。尝试包括jQuery Color动画

这里所有的答案都使用此插件,但没有人提及它。


3

实际上,我有一个只需要jQuery 1.3x且没有aditionnal插件的解决方案。

首先,在脚本中添加以下功能

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一起使用。

注意:在Firefox 3和IE 6上进行了测试(是的,它也适用于旧版本)


2
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插件


过滤器行引发下一个错误。我在表行元素(tr)中使用黄色淡入淡出“ this.style.removeAttribute不是函数[对此错误处中断] this.style.removeAttribute('filter');”
塞尔吉奥·阿莫

2

我讨厌添加23kb只是为了添加effects.core.js和effects.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')。faderEffect();调用它


这与用户要求的黄色渐变不同。
乔恩·温斯坦利

2
对。我建议替代或“类似”。
Corey 2010年

2

这是我解决这个问题的方法。它表现出色。它通过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});
};

1
这比jQuery高亮有什么好处?docs.jquery.com/UI/Effects/Highlight
Nathan Koop,

1
在我的情况下,我不能使用Jquery ui。所以我只用Jquery来解决一个问题。
许多

1

这是非jQuery选项,可用于颜色淡入淡出效果。在“颜色”数组中,添加从初始颜色到最后一种颜色所需的过渡颜色。您可以根据需要添加任意数量的颜色。

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

0

如果您想尝试另一种不依赖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>

0

我只是用...

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

0

一个简单的“黄色淡出”脚本,除了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>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.