javascript - 获取内联 CSS 属性值,即使它被覆盖

标签 javascript jquery html css

我在“样式”属性中有一个带有内联 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/

相关文章:

javascript - jQuery 无法在 Bootstrap 模式下工作

javascript - 显示 json 图像数据的缩略图

div 中的 Jquery 复选框一次选中一个

html - 如何在非输入元素上设置焦点

javascript - capybara 在动态环境中的模糊性

javascript - IE 11 仍然在点击处理程序中没有 .submit() 的情况下提交表单

javascript - GraphQL 术语 "fieldAST"的起源是什么

javascript - 如何自动删除所有文件中 native 不需要的导入?

javascript - 通过jquery制作元素 "css-absolute"时奇怪的跳转

html - Div 是立即扩展而不是随时间扩展?