Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检查div是否有任何背景值?_Javascript_Css_Background - Fatal编程技术网

Javascript 如何检查div是否有任何背景值?

Javascript 如何检查div是否有任何背景值?,javascript,css,background,Javascript,Css,Background,所以我想检查div是否有任何背景值,而不是检查每个值,如: if (item.style.background === "" && item.style.backgroundColor === "" etc. 有什么办法吗?我的主要目标是在div/项没有任何背景时设置白色背景色。欢迎使用StackOverflow 您可以使用hasOwnProperty方法检查是否存在背景或背景色属性 你是这样做的: 如果item.style.hasOwnProperty'background'

所以我想检查div是否有任何背景值,而不是检查每个值,如:

if (item.style.background === "" && item.style.backgroundColor === "" etc.

有什么办法吗?我的主要目标是在div/项没有任何背景时设置白色背景色。

欢迎使用StackOverflow

您可以使用hasOwnProperty方法检查是否存在背景或背景色属性

你是这样做的:

如果item.style.hasOwnProperty'background'&&!item.style.hasOwnProperty'backgroundColor'{ item.style.backgroundColor='白色'; }
您有几个选择,但首先:这取决于您是只关心内联样式,还是还关心通过CSS应用的样式

在下面的示例中,我在元素上使用了style属性,它只有内联样式。如果希望使用CSS中的样式,请在元素上使用getComputedStyle,并使用结果对象而不是下面的style属性。如果您需要支持旧版本的IE,它们没有getComputedStyle,但是它们在元素上有一个currentStyle属性,它可以做很多相同的事情

选择:

一,。只需将您感兴趣的样式名称作为一个数组列出,因为没有那么多,请使用每个或一些:

实例:

函数检查div{ 变量键=[ 背景,背景颜色,背景URL/。。。 ]; if!keys.somek=>Booleandiv.style[k]{ console.logdiv.id+:添加白色背景; }否则{ console.logdiv.id+:不添加; } } checkdocument.getElementByIdexample1; checkdocument.getElementByIdexample2;
使用element.style仅检查内联样式,而不检查计算样式。这是否适用于您的用例?提供一个不能跨浏览器工作的属性,在包括Chrome在内的许多浏览器上,该属性不是自己的属性,而是原型上的访问器。根据MDN,所有浏览器都支持Object.prototype.hasOwnProperty。所以它确实可以跨浏览器工作。早在2014年,Matthew Gertner和JavaScript Garden就已经推荐使用它。根据他们的说法,使用hasOwnProperty是检查对象上是否存在属性的唯一可靠方法。问题不是hasOwnProperty,问题是我在评论中说的:属性不是自己的属性,而是原型上的访问器。这并不是说很难检查在Firefox中运行。有背景色的div和没有背景色的div都说没有,但是如果你访问它,它就在那里:或者蓝色,这取决于它。在Chrome上,情况正好相反:该属性始终是自己的道具,因此检查再次以另一种方式失败。我记错了,在我最初的评论中应该说Firefox而不是Chrome。
var keys = [
  "background", "backgroundColor", "backgroundUrl" // ...
];
if (!keys.some(k => Boolean(div.style[k]))) {
    console.log("Add the white background");
} else {
    console.log("Don't add it");
}