获取计算的样式并省略默认值 [英] Get the computed style and omit defaults

查看:103
本文介绍了获取计算的样式并省略默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取元素的当前运行时风格,并筛选出具有默认值的属性。例如,使用如下标记:

I'm trying to get the current runtime style of an element and filter out properties that have default values. For example, with markup like this:

<style>
    .foo { background: red }
    span { font-size:30px }
</style>


<div style="color: blue">
    <span id="bar" class="foo">hello</span>
</div>

我想要的结果是:

 background-color: red;
 color: blue;
 font-size: 30px;

我尝试了 window.getComputedStyle 返回很多东西,我不确定如何过滤默认值。

I tried window.getComputedStyle, but it returns a lot of stuff and I'm unsure how to filter out defaults. Any pointers will be appreciated.

推荐答案

在这里,
i通过添加一个新的DOM元素知道哪些样式是任何元素的默认样式。

there you go, i did this by adding a new dummy DOM element, to know which styles are default for any element.

/**
 * IE does not have `getComputedStyle` 
 */

window.getComputedStyle = window.getComputedStyle || function( element ) {
  return element.currentStyle;
}

/**
 * get computed style for an element, excluding any default styles
 *
 * @param {DOM} element
 * @return {object} difference
 */

function getStylesWithoutDefaults( element ) {

  // creating an empty dummy object to compare with
  var dummy = document.createElement( 'element-' + ( new Date().getTime() ) );
  document.body.appendChild( dummy );

  // getting computed styles for both elements
  var defaultStyles = getComputedStyle( dummy );
  var elementStyles = getComputedStyle( element );

  // calculating the difference
  var diff = {};
  for( var key in elementStyles ) {
    if( defaultStyles[ key ] !== elementStyles[ key ] ) {
      diff[ key ] = elementStyles[ key ];
    }
  }

  // clear dom
  dummy.remove();

  return diff;
}


/**
 * usage
 */

console.log( getStylesWithoutDefaults( document.getElementById( 'bar' ) ) );

注意


  • 结果将有一些额外的属性,不仅仅是您提到的属性。

a href =http://jsbin.com/docodovo/1/ =nofollow>演示 - 控制台应该打开

demo - console should be opened

这篇关于获取计算的样式并省略默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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