繁体   English   中英

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

[英]How to check if HTML style attribute exists with javascript

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

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

style 对象有一个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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM