获取继承CSS规则的元素 [英] Get element from which CSS rule is being inherited
问题描述
在jQuery中,我们可以使用 css
方法轻松获取给定元素的CSS值:
In jQuery, we can easily get the CSS value for a given element with the css
method:
$('#myElement').css('line-height'); // e.g. '16px'
现在,因为这个CSS值可能是从父元素继承的,所以有没有如何知道哪个元素应用了这个规则?
Now, since this CSS value might have been inherited from a parent element, is there any way to know which element has this rule applied to it?
例如,假设我有以下HTML:
For example, let's say I have the following HTML:
<div class="parent">
<div id="myElement"></div>
</div>
以及以下CSS:
.parent {
line-height: 20px;
}
调用 css
#myElement
上的方法将返回 20px
,但它不会表明它是从继承的.parent
。
Calling the css
method on #myElement
will return 20px
, but it will not indicate that it was inherited from .parent
.
我知道我可以启动 Web Inspector
/ 开发工具
/ Firebug
,但我希望以编程方式获取它。
I know I can just fire up Web Inspector
/Dev Tools
/Firebug
, but I want to get it programmatically.
这一切都可能吗?
推荐答案
走上parentElement链,检查每个元素的css()值。具有不同的父()。css()值的第一个元素(可能)是CSS规则选择器所针对的元素。
Walk up the parentElement chain checking the css() value of each element. The first element with a parent().css() value that's different is (probably) the element being targeted by the CSS rule selector.
请参阅此小提琴以获取示例: http://jsfiddle.net/broofa/VPWV9/2/ (请参阅控制台。日志输出)
See this fiddle for an example: http://jsfiddle.net/broofa/VPWV9/2/ (See the console.log output)
(注意:几乎肯定会出现一些复杂的情况,这种情况不能按预期工作,但对于上述情况,它可以正常工作。)
(Note: there are almost surely complex cases where this won't work as expected but for the case as described, it works.)
这篇关于获取继承CSS规则的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!