Html 如何使用javascript检查HTML样式属性是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18635213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if HTML style attribute exists with javascript
提问by Biffy
I'm trying to find out if a specific element has an inline style attribute or not: I'm sure there's an easy method to check this, but I can't seem to find it. I tried multiple things already including this:
我试图找出特定元素是否具有内联样式属性:我确定有一种简单的方法可以检查这一点,但我似乎找不到它。我已经尝试了很多事情,包括这个:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");
Thank you for your help!
感谢您的帮助!
采纳答案by wakqasahmed
if(!contentWrapper.getAttribute("style"))
OR
或者
if(contentWrapper.getAttribute("style")==null ||
contentWrapper.getAttribute("style")=="")
the above lines will work for you (anyone can be chosen).
以上几行对你有用(任何人都可以选择)。
In second solution:
在第二种解决方案中:
first check watches if style attribute
is present in the element, 2nd check ensures that style attribute
is not present as an empty string
e.g. <div id="contentWrapper" style="">
首先检查style attribute
元素中是否存在,第二次检查确保它style attribute
不作为empty string
例如存在<div id="contentWrapper" style="">
Complete code is given below:
完整代码如下:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.getAttribute("style")==null || contentWrapper.getAttribute("style")=="")
alert("Empty");
else
alert("Not Empty");
http://jsfiddle.net/mastermindw/fjuZW/(1st Solution)
http://jsfiddle.net/mastermindw/fjuZW/(第一个解决方案)
http://jsfiddle.net/mastermindw/fjuZW/1/(2nd Solution)
回答by Praind
if(contentWrapper.getAttribute("style")){
if(contentWrapper.getAttribute("style").indexOf("display:") != -1){
alert("Not Empty");
} else {
alert("Empty");
}
}
回答by jozxyqk
I missed @plalx's comment the first time I scanned this page.
我第一次扫描此页面时错过了@plalx 的评论。
if (element.hasAttribute("style"))
{
var styleText = element.getAttribute("style")
}
On a related note, regarding styles...
在相关说明中,关于样式...
//to get info about the end results of CSS
var computedStyle = element.currentStyle || getComputedStyle(element, null);
and
和
//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);