使用JQuery实现黄色渐变效果

104
我希望能够实现类似于37Signals的黄色淡出效果。我正在使用Jquery 1.3.2版本。以下是代码:
(function($) {
   $.fn.yellowFade = function() {
    return (this.css({backgroundColor: "#ffffcc"}).animate(
            {
                backgroundColor: "#ffffff"
            }, 1500));
   }
 })(jQuery);

接下来的调用会展示黄色淡入淡出DOM元素,该元素的id为box

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

但是它只会让它变成黄色。15000毫秒后没有白色背景。你有什么想法为什么它不起作用吗?
解决方案:
你可以使用:
$("#box").effect("highlight", {}, 1500);

但是您需要包括:

effects.core.js
effects.highlight.js


请注意,源代码在此处:https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.effect-highlight.js - styfle
15个回答

101

1
我在jquery网站上看到了演示:http://docs.jquery.com/UI/Effects/Highlight#overview我已经在我的代码中尝试过,但没有任何反应。我需要下载额外的内容吗?它说依赖于Effects Core。这是另一个插件吗? - Sergio del Amo
回答正确,但我想提一下它是内置函数于jQuery effects.core.js中,而不是核心jQuery文件像animate()。只是觉得值得澄清。 - Steerpike
5
嘿,正如Sergio显然刚发现的那样...是的,Sergio,你需要包含effects.core.js文件和effects.highlight.js(在这里检查源代码:http://docs.jquery.com/UI/Effects/Highlight)。 - Steerpike
2
该功能可在jQuery UI中使用:http://docs.jquery.com/UI/Effects/Highlight#overview - Matt Scilipoti
7
更新之前的评论,现在您不再需要包含effects.core.js和effects.highlight.js(旧的URL已经失效)。现在的方法是包含jQuery-UI库:http://code.jquery.com/ui/1.10.4/jquery-ui.min.js - Sean Colombo
显示剩余2条评论

68

我喜欢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
我喜欢这个解决方案。在表格的行上效果很好。 - Perry Tew
到目前为止,这是最好的解决方案。如果它也能复制元素的边框半径,那就更好了。 - Stijn Van Bael
@StijnVanBael 代码已更新以复制边框半径。感谢您的建议。 - Doug S
不错,但似乎在像FeatherlightJs这样的模态框上无法正常工作。 - Ryan
喜欢这段代码片段! :-) - scp
显示剩余2条评论

65

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
3
更新:当尝试突出显示浮动元素(例如,当元素为“float:right”时)时,此代码通常会失败。因此,我重写了代码,以便无论元素在页面上的位置如何,都可以正确地显示突出显示:https://dev59.com/qHRA5IYBdhLWcg3wuAcp#13106698 - Doug S
2
不错的轻量级解决方案 - 运行得非常好。我发现我的高亮并没有包括元素的填充,所以我使用了 .width(el.outerWidth()).height(el.outerHeight()) 来突出显示整个表单字段。 - Mark B
感谢Mark提供的填充解决方案。我注意到还有一个问题,生成的div的z-index可能比现有的div更高,因此我在不透明度后添加了以下行:'"z-index": -1000'以确保生成的div在后面。 - WtFudgE
将 return $(this); 添加到代码中,使其能够在调用 .highlight() 后调用其他函数。 - WickStargazer
显示剩余5条评论

15

按照以下方式定义您的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);

这应该可以解决问题。将其设置为黄色,然后将其淡化为白色。


谢谢你的回答。但是它并没有起作用。似乎 animate 没有做任何事情。 - Sergio del Amo
你使用的是哪个版本的jQuery? - user83632
1.3.2. 我把这个添加到了我的问题中。 - Sergio del Amo
这对我的需求非常适用,除了基本的jquery没有其他依赖。 - gojomo
3
这需要使用jQuery.Color()插件才能正常工作:https://github.com/jquery/jquery-color - Dia Kharrat
我认为这是最优雅的解决方案。 - someuser

8

我刚刚在一个项目中解决了类似的问题。默认情况下,animate函数无法对颜色进行动画处理。尝试包含jQuery Color Animations

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


3

实际上,我有一个解决方案,只需要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兼容。

注意:在Firefox 3和IE 6上测试过(是的,在那个古老的东西上也能运行)


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 Highlight有什么优势呢?http://docs.jquery.com/UI/Effects/Highlight - Nathan Koop
1
在我的情况下,我不能使用Jquery UI。所以我只能用Jquery修复一个解决方案。 - many

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中的反锯齿bug。

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

YellowFade('#myDivId');
信用: Phil Haack演示了如何做到这一点。他在演示JQuery和ASPNet MVC。

观看此视频

更新: 你看过这个视频吗?我忘了提到这需要JQuery.Color插件


下一个错误由过滤器行抛出。我正在使用黄色淡入表行元素(tr)“this.style.removeAttribute不是函数[在此错误上中断] this.style.removeAttribute('filter');”。 - Sergio del Amo

2

我讨厌为了加入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()调用它。


这与用户所需的黄色渐变不同。 - Jon Winstanley
2
没错。我建议一个替代方案或“类似的东西”。 - Corey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接