获取尚未应用的类的CSS属性值 [英] Get CSS properties values for a not yet applied class

查看:174
本文介绍了获取尚未应用的类的CSS属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中,我可以使用 css 方法获取一个CSS属性值,并传递一个属性名称,例如:

In jQuery, I can get a CSS property value for a selector using the css method and passing a property name, for example:

$('#myElement')。css('backgroundImage');

我从的类中获取css属性值,但应用于任何元素?类似于 $('。myClass')。css('backgroundImage'); 其中选择器返回零元素,但是有一个CSS声明。

My question is, how can I get a css property value from a class that is not yet applied to any element? Similar to $('.myClass').css('backgroundImage'); where the selector returns zero elements but there is a CSS declaration for that class.

推荐答案

您可以创建一个临时元素,而无需将其添加到DOM中,并检查相关属性。 CSS将应用,即使元素没有添加到DOM。例如

You can create a temporary element without adding it to the DOM, and inspect the relevant property. CSS will apply, even if the element is not added to the DOM. E.g.

CSS

p { color: red; }

JS

var p = document.createElement('p');
alert(window.getComputedStyle(p, null).getPropertyValue('color'));

会为您提供颜色值,但不会向DOM添加任何内容。

will give you the color value, but not add anything to the DOM.

警告

经过一番研究,我确定此方法仅适用于Gecko-基于浏览器,因此不适合通用目的使用。这种情况可能会在将来更改,但我不会如果你今天想要一个跨浏览器的解决方案,那就不要这样了。

After a bit of research, I've determined that this method only works in Gecko-based browsers, so is not suitable for general-purpose use. This situation may change in future, but I wouldn't rely on this if you want a cross-browser solution today.

鉴于此,我建议你只创建一个临时元素,添加所需的类,添加它到文档,检查它获取样式值,然后删除它。您还可以应用样式,例如 display:none ,以防止在其作为文档一部分的非常短暂的时间内向用户显示。

Given that, I would suggest you just create a temporary element, add the desired class, add it to the document, inspect it to get the style value, then remove it. You can additionally apply styles such as display: none to prevent it from being shown to the user during the incredibly brief time that it's part of the document.

这篇关于获取尚未应用的类的CSS属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆