jQuery更改背景颜色


129

我正在尝试使用此示例的jQuery:

 $(document).ready(function(){
      $("button").mouseover(function(){
        $("p#44.test").css("background-color","yellow");
        $("p#44.test").hide(1500);
        $("p#44.test").show(1500);
        $("p#44.test").css("background-color","red");
      });
    });

我预计会发生以下情况:

1. Color of <p> to turn yellow
2. <p> to slowly fade
3. <p> to slowly show
4. Color of <p> to turn red

但这是实际发生的情况:

1. <p> turned red
2. <p> slowly hid away
3. <p> slowly showed

这是为什么?

Answers:


209

.css()函数不会在正在运行的动画后面排队,它是瞬时的。

要匹配您的行为,您需要执行以下操作:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

.queue()函数等待正在运行的动画用完,然后触发提供的函数中的所有内容。


20

这应该是这样的:

码:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

演示: http //jsfiddle.net/p7w9W/2/

说明:

在切换背景色之前,您必须等待动画功能的回调。您也不应仅使用数字ID :,并且如果您使用的是ID,<p>则不应在选择器中包含类。

我还增强了您的代码(jQuery对象的缓存,链接等)

更新: 根据VKolev的建议,当隐藏项目时,颜色现在正在更改。


设置$ p.css(“ background-color”,“ red”); 在$ p.show之前会变得更好一点,再次显示p内容后没有闪烁效果。
VKolev

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.