最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.getComputedStyle(): How to Discard properties with default values? - Stack Overflow

programmeradmin3浏览0评论

Hi I am developing an extension for Google Chrome and am using window.getComputedStyle() to get a particular property of a DOM element. This way, I am getting multiple properties and building a CSS. I want to discard the properties with default values. How can I do that? How can I know the default value of a property?

Hi I am developing an extension for Google Chrome and am using window.getComputedStyle() to get a particular property of a DOM element. This way, I am getting multiple properties and building a CSS. I want to discard the properties with default values. How can I do that? How can I know the default value of a property?

Share Improve this question asked Dec 17, 2010 at 14:57 U.PU.P 7,4427 gold badges41 silver badges63 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Looking through the chromium source led me to: node.ownerDocument.defaultView.getMatchedCSSRules(node, '');

I used it to create this function that will return only the styles defined by the style property or a matched CSS rule. Anything that appears in getComputedStyle but not here would be default, but I'm guess that this returns what you are actually looking for: the styles without the defaults.

// WebKit only
function getStyle(node) {
  var styles = {};
  var rules = node.ownerDocument.defaultView.getMatchedCSSRules(node, '');

  var i = rules.length;
  while (i--) {
    merge(styles, rules[i].style)
  }
  merge(styles, node.style);

  return styles;

  function merge(obj, style) {
    var i = style.length;
    while(i--) {
      var name = style[i];
      obj[name] = style.getPropertyCSSValue(name);
    }
  }
}

This may be very, very tough, as there is no single way to tell where an element's CSS rules e from. putedStyle mixes them all together to show the end result. Default values are by definition hard to pick out from that.

I have an alternative idea - if it applies in your situation:

  • Programmatically disable every style sheet involved in the page for a second. Disable all inline <style> elements from the DOM.

  • If, when all style sheets have been disabled, the putedStyle of the element is unchanged, you're dealing with a default value.

You could even find out which style sheets contain rules applying to an element, by disabling the style sheets one by one, and keeping track of whether the putedStyle changes.

This is obviously rather plex and slow, but it's the only safe way I can think of.

发布评论

评论列表(0)

  1. 暂无评论