JQuery 的黄色淡入淡出效果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/848797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:55:20  来源:igfitidea点击:

Yellow fade effect with JQuery

jquery

提问by Sergio del Amo

I would like to implement something similar to 37Signals's Yellow Fade effect.

我想实现类似于37Signals 的黄色淡入淡出效果的东西。

I am using Jquery 1.3.2

我正在使用 Jquery 1.3.2

The code

编码

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

and the next call show yellow fade the DOM elment with boxid.

下一个调用显示黄色淡出带有ID的 DOM 元素。

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

But it only makes it yellow. No white background after 15000 milliseconds.

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

Any idea why it is not working?

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

Solution

解决方案

You can use:

您可以使用:

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

But you would need to include:

但你需要包括:

effects.core.js
effects.highlight.js

effects.core.js
effects.highlight.js

采纳答案by Baldu

This function is part of jQuery effects.core.js:

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

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

As Steerpike pointed out in the comments, effects.core.jsand effects.highlight.jsneed to be included in order to use this.

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

回答by Doug S

I loved Sterling Nichols answer, since it was lightweight and didn't require a plugin. However, I discovered it didn't work with floating elements (i.e. such as when the element is "float:right"). So I re-wrote the code to display the highlight properly no matter how the element is positioned on the page:

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

Optional:
Use the following code if you also want to match the border-radius of the element:

可选:
如果您还想匹配元素的边框半径,请使用以下代码:

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

回答by Sterling Nichols

The jQuery effects library adds quite a bit of unneeded overhead to your app. You can accomplish the same thing with jQuery only. http://jsfiddle.net/x2jrU/92/

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

回答by Kamran Ahmed

Define your CSS as follows:

定义你的 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;
}

And just add the class yftto any item $('.some-item').addClass('yft')

只需将类添加yft到任何项目$('.some-item').addClass('yft')

Demo: http://jsfiddle.net/Q8KVC/528/

演示:http: //jsfiddle.net/Q8KVC/528/

回答by Kamran Ahmed

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

Should do the trick. Set it to the yellow, then fade it to white

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

回答by Travis

I just solved a problem similar to this on a project I was working on. By default, the animate function cannot animate colors. Try including jQuery Color Animations.

我刚刚在我正在从事的项目中解决了与此类似的问题。默认情况下,animate 函数不能为颜色设置动画。尝试包括jQuery Color Animations

All the answers here use this plugin but no one mentions it.

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

回答by Travis

Actually, I have a solution that only needs jQuery 1.3x, and no aditionnal plugin.

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

First, add the following functions to your script

首先,将以下函数添加到您的脚本中

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

Next, call the function using this:

接下来,使用这个调用函数:

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

I'll let you guess the parameters, they are pretty self explanatory. To be honest the script is not from me, I took it on a page then changed it so it works with the latest jQuery.

我会让你猜测参数,它们是不言自明的。老实说,这个脚本不是我写的,我把它放在一个页面上,然后对其进行了更改,以便它可以与最新的 jQuery 一起使用。

NB: tested on firefox 3 and ie 6 (yes it works on that old thing too)

注意:在 firefox 3 和 ie 6 上测试过(是的,它也适用于那个旧东西)

回答by Corey

I hated adding 23kb just to add effects.core.js and effects.highlight.js so I wrote the following. It emulates the behavior by using fadeIn (which is part of jQuery itself) to 'flash' the element:

我讨厌添加 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); 
        });
    });
}

then call it with $('.item').faderEffect();

然后用 $('.item').faderEffect(); 调用它

回答by Vin

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');
              });
}

The line this.style.removeAttribute('filter')is for an anti-aliasing bug in IE.

该行this.style.removeAttribute('filter')用于 IE 中的抗锯齿错误。

Now, call YellowFade from wherever, and pass your selector

现在,从任何地方调用 YellowFade,然后传递您的选择器

YellowFade('#myDivId');

Credit: Phil Haack had a demo showing exactly how to do this. He was doing a demo on JQuery and ASPNet MVC.

信用:Phil Haack 有一个演示,展示了如何做到这一点。他正在做一个关于 JQuery 和 ASPNet MVC 的演示。

Take a look at this video

看看这个视频

Update: Did you take a look at the video? Forgot to mention this requires the JQuery.Color plugin

更新:你看视频了吗?忘了说这需要JQuery.Color 插件

回答by many

this is my solution for the problem. it works excelent. it passes jslint error validation and also works decent in IE8 and IE9. Of course you can tweak it to accept color codes and callbacks:

这是我对问题的解决方案。它工作得很好。它通过了 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});
};