如何使用javascript检查HTML样式属性是否存在

How to check if HTML style attribute exists with javascript

本文关键字:属性 是否 存在 样式 HTML 何使用 javascript 检查      更新时间:2023-09-26

我正试图了解特定元素是否具有内联样式属性:我确信有一个简单的方法可以检查这个,但我似乎找不到。我已经尝试了多种方法,包括:

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 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");

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

http://jsfiddle.net/mastermindw/fjuZW/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);

样式对象有一个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

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

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