首页 > 解决方案 > 如何将所有计算样式设置为元素上的文字样式?

问题描述

这个问题与 SO 上的这个问题类似(我认为):How to move all computed CSS styles from a element and apply them to another element using JavaScript?

我想要做的是找到所有通过 css 表应用的样式,并在元素上显式设置(如使用 style= 属性)。我想这样做的原因是,如果我在那里打开它,MS 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 时,我收到一条错误消息“无效的调用对象”。我不明白问题出在哪里

标签: javascriptjquerycssstyles

解决方案


好吧,以下代码片段可以满足您的需求,尽管我认为这不是您所需要的。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>


推荐阅读