简体   繁体   English

jQuery无法识别#FFFFFF的背景色

[英]JQuery isn't recognizing background color of #FFFFFF

I'm trying to build a quick thingy where the web page changes color every time you click a button. 我正在尝试构建一个快速的东西,每次单击按钮时网页都会更改颜色。 I've written JS which will change the bg color to red if the current bg is #FFFFFF. 我写了JS,如果当前的bg是#FFFFFF,它将把bg的颜色改为红色。 After it didn't work with the default, I tried explicitly setting the bg color through CSS and HTML script tag to #FFFFFF. 在默认设置不起作用之后,我尝试通过CSS和HTML脚本标记将#8颜色显式设置为#FFFFFF。 Neither worked. 两者都不起作用。 Oddly, the JS runs if I change the == operator to !==. 奇怪的是,如果我将==运算符更改为!==,则JS将运行。

  $(document).ready(function() { $("button").click(function() { if ($("body").attr("background-color") == "#FFFFFF") { $("body").css("background-color", "red"); } else if ($("body").attr("background-color") == "red") { }; }); }); 
 body { background-color: #FFFFFF; } 
 <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <title></title> </head> <body style="background-color:#FFFFFF;"> <button>hi</button> <div class="test">text</div> </body> </html> 

You can't use attr to retrieve a style property, you have to css instead : 您不能使用attr来检索样式属性,而必须使用css
$("body").css("background-color")

more informations here : https://api.jquery.com/css/ 此处提供更多信息: https : //api.jquery.com/css/

It is not attribute, it is style that you checking. 它不是属性,而是您检查的样式。 Attributes are inside tags, styles are inside css. 属性在标签内部,样式在css内部。 Use $("body").css("background-color") 使用$("body").css("background-color")

You are checking for a background-color attribute on the body. 您正在检查主体上的background-color属性。 Body doesn't have a background-color attribute. 主体没有背景颜色属性。 It has a style attribute - which in turn has a background-color attribute. 它具有样式属性-依次具有背景颜色属性。

Option 1: Change your if statement to check for the style: 选项1:更改if语句以检查样式:

if ($("body").attr("style") == "background-color: #FFFFFF;")
  • This will only work if you don't add additional styles. 仅当您不添加其他样式时,这才起作用。 You are better off using Option 2 below. 您最好使用下面的选项2。

Option 2: Set the color via a css class, then check whether the body has that class. 选项2:通过CSS类设置颜色,然后检查主体是否具有该类。

CSS:
.white { background-color: #FFFFFF; }
.red { background-color: red; }

JQUERY:
if ($("body").hasClass("white")) {
    $("body").removeClass("white").addClass("red");
}

尝试这个:

   $("body").css("background-color", "#FFFFFF");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM