我对 Jquery 有点陌生,我遇到了一个问题......
在下面的代码中 - if 语句不应该出现在 ELSE 语句中,因为 $(this).css("color") ==="red") ...
https://jsfiddle.net/roybarak/7mLsot7k/
我的代码出了什么问题?
TNX,罗伊。
最佳答案
快速使用console.log($(this).css("color"));
告诉你该段落的颜色是“rgb(255, 0, 0)” ,至少根据 Chrome 的说法是这样。正如下面引用的文档中所述,不同的浏览器可能会以不同的格式返回颜色。
我修改了 if
语句以包含我认为最常见的“red”版本:
$("p").click(function () {
if ($(this).css("color").toLowerCase() == "rgb(255, 0, 0)"
|| $(this).css("color").toLowerCase() == '#ff0000'
|| $(this).css("color").toLowerCase() == '#f00') {
alert("this is red");
} else {
alert("this is not red");
}
});
来自the documentation的重要部分,正如用户 Vohuman 所指出的:
"Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as em, ex, px or % in a style sheet. Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255)."
关于javascript - jquery if 语句返回 return Wearg 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29503794/