这个问题类似于(我认为)关于 SO 的这个问题:How to move all computed CSS styles from one element and apply them to a different 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 时,我收到一条错误消息“无效的调用对象”。我不明白这是什么问题
最佳答案
好吧,下面的代码片段可以满足您的需求,但我认为这不是您所需要的。 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>
关于javascript - 如何将所有计算样式设置为元素上的文字样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51046925/