我试图找出特定元素是否具有内联样式属性: 我确定有一个简单的方法来检查这个,但我似乎无法找到它。 我尝试了很多东西,包括:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");
感谢您的帮助!
答案 0 :(得分:8)
if(contentWrapper.getAttribute("style")){
if(contentWrapper.getAttribute("style").indexOf("display:") != -1){
alert("Not Empty");
} else {
alert("Empty");
}
}
答案 1 :(得分:1)
if(!contentWrapper.getAttribute("style"))
OR
if(contentWrapper.getAttribute("style")==null ||
contentWrapper.getAttribute("style")=="")
上述行将适合您(任何人都可以选择)。
在第二个解决方案中:
如果元素中存在style attribute
,首先检查监视,第二次检查确保style attribute
不存在empty string
,例如<div id="contentWrapper" style="">
完整代码如下:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.getAttribute("style")==null || contentWrapper.getAttribute("style")=="")
alert("Empty");
else
alert("Not Empty");
答案 2 :(得分:0)
第一次扫描此页面时,我错过了@ 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);
答案 3 :(得分:0)
样式对象有一个 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
答案 4 :(得分:0)
检查给定Id的样式属性是否存在
if(document.getElementById("idname").hasAttribute("style")){
alert("Style attribute found");
}else{
alert("Style attribute not found");
}