我正在尝试查找特定元素是否具有内联样式属性:
我相信有一种简单的方法来检查这一点,但我似乎找不到它。
我已经尝试了多种方法,包括以下内容:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");
感谢你的帮助!
我正在尝试查找特定元素是否具有内联样式属性:
我相信有一种简单的方法来检查这一点,但我似乎找不到它。
我已经尝试了多种方法,包括以下内容:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");
感谢你的帮助!
if(contentWrapper.getAttribute("style")){
if(contentWrapper.getAttribute("style").indexOf("display:") != -1){
alert("Not Empty");
} else {
alert("Empty");
}
}
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");
null
和''
都是假值。此外,https://developer.mozilla.org/en-US/docs/Web/API/element.hasAttribute 更好。 - plalxBoolean('')
是false
。所以if (!contentWrapper.getAttribute('style')) { //empty }
适用于null
或''
。 - plalx检查给定 Id 是否存在样式属性
if(document.getElementById("idname").hasAttribute("style")){
alert("Style attribute found");
}else{
alert("Style attribute not found");
}
我第一次浏览这个页面时错过了 @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);
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
getAttribute('style')
- Virus721display.toString == ""
正在比较函数,而您想要比较的是函数的返回值。应该是display.toString() == ""
。(无论如何,在这里您都不需要.toString()
,因为display
已经是一个字符串,但这是您的代码可能失败的另一个原因) - freefaller