代码之家  ›  专栏  ›  技术社区  ›  ControlAltDel

如何将元素上的所有计算样式设置为文字样式?

  •  0
  • ControlAltDel  · 技术社区  · 8 年前

    这个问题(我认为)与下面这个问题类似: How to move all computed CSS styles from one element and apply them to a different element using JavaScript?

    我要做的是找到所有通过css工作表应用的样式,并显式地(如使用style=属性)设置元素。我想这样做的原因是,如果我在那里打开word(2010)的话,它会选择样式

    这是我的密码

    var $this = $(this);
    var styles = window.getComputedStyle(this, null);
    $this.css(styles);
    

    我也试过

    var styles = document.defaultView.getComputedStyle(this, null);
    

    当我在最后一行($this.css(styles))放置一个try-catch时,得到一条错误消息“invalid calling object”。我不明白问题出在哪里

    1 回复  |  直到 8 年前
        1
  •  1
  •   Kosh    8 年前

    好吧,下面的代码片段是你想要的,尽管我不认为这是你需要的。ms word不是浏览器,我不确定它是否支持所有样式,或者jquery是否在那里工作……

    var $this = $('b');
    var styles = window.getComputedStyle($this[0]);
    
    $this.css(
      Object.values(styles).reduce(
        (a, e) => 0*(a[e] = styles[e]) || a, {}
      )
    )
    
    console.log(`style="${$this.attr('style')}"`)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <b>I have styles</b>
    推荐文章