jQuery 更改背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4283141/
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 16:59:30  来源:igfitidea点击:

Jquery change background color

jquery

提问by aWebDeveloper

I was trying out jquery with this example:

我正在用这个例子尝试 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");
      });
    });

I expected the following to happen:

我预计会发生以下情况:

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

But this is what actually happened:

但实际发生的事情是这样的:

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

Why is that?

这是为什么?

回答by Klemen Slavi?

The .css()function doesn't queue behind running animations, it's instantaneous.

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

To match the behaviour that you're after, you'd need to do the following:

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

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

The .queue()function waits for running animations to run out and then fires whatever's in the supplied function.

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

回答by Peter ?rneholm

This is how it should be:

应该是这样:

Code:

代码:

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

Demo:http://jsfiddle.net/p7w9W/2/

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

Explanation:

解释:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p>there you shouldn't include a class in your selector.

在切换背景颜色之前,您必须等待动画函数的回调。你也不应该只使用数字 ID:s,如果你有一个 ID,你<p>不应该在你的选择器中包含一个类。

I also enhanced your code (caching of the jQuery object, chaining, etc.)

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

Update:As suggested by VKolevthe color is now changing when the item is hidden.

更新:正如VKolev所建议的,当项目隐藏时,颜色现在会发生变化。

回答by austinbv

try putting a delay on the last color fade.

尝试延迟最后一次褪色。

$("p#44.test").delay(3000).css("background-color","red");

What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!

HTML 中 id 属性的有效值是什么?
ID不能以数字开头!!!