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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:30:58  来源:igfitidea点击:

Get inline-style value even if element has the value also set in CSS?

javascriptjquery

提问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 !importantmodifier. If you must instead try and retrieve the in-line style, regardless of whether it was applied or not, you can simply use the styleobject of the element node:

请注意,这将获得获胜的样式,在这种情况下将是带有!important修饰符的样式。如果您必须尝试检索内联样式,无论是否应用,您都可以简单地使用style元素节点的对象:

inlineWidth = span.style.width;

JS Fiddle demo.

JS小提琴演示

Do remember that, for widthto be applied to a spanelement, it must be either display: blockor display: inline-block.

请记住,width要应用于span元素,它必须是display: blockdisplay: inline-block