如何使用JavaScript检查HTML的style属性是否存在

16

我正在尝试查找特定元素是否具有内联样式属性:

我相信有一种简单的方法来检查这一点,但我似乎找不到它。

我已经尝试了多种方法,包括以下内容:

var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");

感谢你的帮助!


1
可能是重复的问题:如何在Jquery中检查属性是否存在 - InspiredCoder
1
getAttribute('style') - Virus721
此外,在调用函数时要小心,确保添加括号。display.toString == ""正在比较函数,而您想要比较的是函数的返回值。应该是display.toString() == ""。(无论如何,在这里您都不需要.toString(),因为display已经是一个字符串,但这是您的代码可能失败的另一个原因) - freefaller
1
这两个链接提供了jQuery的解决方案,而用户并没有明确要求;因此,这不是那些问题的重复。 - Josh Mein
5个回答

19
if(contentWrapper.getAttribute("style")){
    if(contentWrapper.getAttribute("style").indexOf("display:") != -1){
        alert("Not Empty");
    } else {
        alert("Empty");
    }
}

1
这对于像这样的注释字符串“/* font-size: 24px; */”并不完美。在这种情况下,它会像font-size存在一样工作。 - LarAng

8
if(!contentWrapper.getAttribute("style"))

或者

if(contentWrapper.getAttribute("style")==null || 
   contentWrapper.getAttribute("style")=="")    

上述代码适用于您(任何人都可以选择)。

在第二种解决方案中:

首先检查观察者是否存在元素中的style属性,第二个检查确保style属性不存在为空字符串,例如<div id="contentWrapper" style="">

完整代码如下:

var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.getAttribute("style")==null || contentWrapper.getAttribute("style")=="")
alert("Empty");
else
alert("Not Empty");

http://jsfiddle.net/mastermindw/fjuZW/(第一种解决方案)

http://jsfiddle.net/mastermindw/fjuZW/1/(第二种解决方案)


2
双重检查是不必要的,因为null''都是假值。此外,https://developer.mozilla.org/en-US/docs/Web/API/element.hasAttribute 更好。 - plalx
第二个检查是确保样式属性不为空字符串,例如<div id="contentWrapper" style="">。 - wakqasahmed
2
我知道,但我的意思是Boolean('')false。所以if (!contentWrapper.getAttribute('style')) { //empty }适用于null'' - plalx

1

检查给定 Id 是否存在样式属性

if(document.getElementById("idname").hasAttribute("style")){
  alert("Style attribute found");
}else{
  alert("Style attribute not found");
}

1

我第一次浏览这个页面时错过了 @plalx 的评论。

if (element.hasAttribute("style"))
{
    var styleText = element.getAttribute("style")
}

有关样式方面的相关说明...
//to get info about the end results of CSS
var computedStyle = element.currentStyle || getComputedStyle(element, null);

并且

//to iterate over css styles from style tags or linked CSS
for i ...
    document.styleSheets[i].rules ...

//great for searching with
var elements = document.querySelectorAll(rules[i].selectorText);

1
样式对象具有一个length属性,告诉您元素是否具有任何内联样式。这也避免了存在但为空的style属性的问题。
// Would be 0 if no styles are applied and > 0 if there are inline styles applied
contentWrapper.style.length
// So you can check for it like this
contentWrapper.style.length === 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接