javascript 即使元素在 CSS 中也设置了内联样式值,也要获取内联样式值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19136835/
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
Get inline-style value even if element has the value also set in CSS?
提问by user2413333
If you have the following element:
如果您有以下元素:
<span style="width:100px"></span>
and the css is:
和 css 是:
span {width:50px!important;}
Is there a way I can get the inline-style value and ignore the css value?
有没有办法可以获取内联样式值并忽略 css 值?
Thanks
谢谢
回答by gp.
use element.style.width
利用 element.style.width
sample:
样本:
$(function(){
alert($("span")[0].style.width);
});
回答by David says reinstate Monica
To find the applied style:
要查找应用的样式:
var span = document.querySelector('span[style]'),
actualWidth = window.getComputedStyle(span, null).width;
Note that this gets the style which won, which in this case will be the one with the !important
modifier. If you must instead try and retrieve the in-line style, regardless of whether it was applied or not, you can simply use the style
object of the element node:
请注意,这将获得获胜的样式,在这种情况下将是带有!important
修饰符的样式。如果您必须尝试检索内联样式,无论是否应用,您都可以简单地使用style
元素节点的对象:
inlineWidth = span.style.width;
Do remember that, for width
to be applied to a span
element, it must be either display: block
or display: inline-block
.
请记住,width
要应用于span
元素,它必须是display: block
或display: inline-block
。