如何获得计算样式和此规则的来源? [英] How to get computed style and the source of this rule?

查看:19
本文介绍了如何获得计算样式和此规则的来源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取元素计算样式和应用该规则的 css(文件和行).类似于 Chrome Dev Tools 在使用计算"​​选项卡并单击值旁边的箭头时所做的操作.

I want to get the element computed style and the css (file and line) that applies that rule. Similar to what Chrome Dev Tools does when the "Computed" tab is used and you click on that arrow beside the value.

简而言之,我希望能够使用 javascript 找出这两件事:

In short, I want to be able to, using javascript, find out these two things:

  1. 实际应用于该元素的 CSS 值是什么(计算样式)
  2. 找到计算样式后,我想知道它来自哪里(例如文件名和行号)

我知道这可以使用 devtools 手动完成,但我需要通过脚本完成.

I know this can be done manually using devtools, but I need this done by a script.

谢谢

推荐答案

您可以使用 Window.getComputedStyle().用法示例:

You can use Window.getComputedStyle(). An example of usage:

<style>
 #elem-container{
   position: absolute;
   left:     100px;
   top:      200px;
   height:   100px;
 }
</style>

<div id="elem-container">dummy</div>
<div id="output"></div>  

<script>
  function getTheStyle(){
    var elem = document.getElementById("elem-container");
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = theCSSprop;
   }
  getTheStyle();
</script>

请参阅 MDN 文档以了解更多如何使用此功能与不同浏览器的兼容性.

See MDN Documentation to learn more how to use this feature and it's compatibility with different browsers.

不幸的是,这种方法不会为您提供此值的来源位置.

Unfortunately, this approach will not give you the location of where this value comes from.

这篇关于如何获得计算样式和此规则的来源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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