我在“样式”属性中有一个带有内联 CSS 代码的元素。我向该元素添加了一个类,该类使用 CSS 样式表中的 !important
覆盖了内联样式。
问题:如何获取内联 CSS 属性值,即使它已被样式表中的 CSS 覆盖?
当我使用 $("div").css("background-size");
它从样式表 CSS 中获取值,而不是被覆盖的内联 CSS。
最佳答案
因为 jQuery 使用 computedStyles 来获取应用于元素的样式。我相信访问 DOM 元素可能是一个“解决方案”
console.log(
$('p').get(0).style.fontSize
);
p {
font-size:20px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p style="font-size:40px;">Hello World</p>
您也可以扩展 jQuery 函数。
jQuery.fn.cssInline = function(prop) {
var e = $(this[0]).get(0); // get DOM element
// convert to camelCase; this may not be required.
var propCamelCase = prop.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
return e.style[propCamelCase];
};
console.log( $('p').cssInline('font-size') );
console.log( $('p').cssInline('fontSize') );
console.log( $('p').cssInline('width') );
p {
font-size:20px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p style="font-size:40px;">Hello World</p>
关于javascript - 获取内联 CSS 属性值,即使它被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39756999/