简体   繁体   English

即使元素具有也在CSS中设置的值,也获得内联样式的值?

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

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 谢谢

use element.style.width 使用element.style.width

sample: 样品:

$(function(){
    alert($("span")[0].style.width);
});

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. 请注意,这将获得制胜的样式,在这种情况下,它将是具有!important修饰符的样式。 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: 如果您必须尝试检索内联样式,而不管是否应用了该style ,则可以简单地使用元素节点的style对象:

inlineWidth = span.style.width;

JS Fiddle demo . JS小提琴演示

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: blockdisplay: inline-block

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

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