简体   繁体   English

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

[英]How to set all computed styles as literal styles on an element?

This question is similar (I think) to this question on SO: How to move all computed CSS styles from one element and apply them to a different element using JavaScript? 这个问题类似于(我认为)关于SO的问题: 如何将所有计算出的CSS样式从一个元素移到并使用JavaScript将其应用于另一个元素?

What I want to do is find all styles that have been applied by way of css sheets and set the explicitly (as in using a style= attribute) on the element. 我想做的是找到所有通过CSS工作表应用的样式,并在元素上显式设置(如使用style =属性一样)。 The reason I want to do this is so that MS Word (2010) will pick up the styling if I open it there 我要这样做的原因是,如果我在其中打开样式,MS Word(2010)将会采用该样式

Here's my code 这是我的代码

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

I also tried with 我也尝试过

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

When I put a try catch around the last line ($this.css(styles), I am getting an error message "invalid calling object". I don't understand what the problem is 当我尝试捕获最后一行($ this.css(styles)时,出现错误消息“无效的调用对象”。我不明白问题是什么

Well, the following snippet does what you want, though I don't think it's what you needed. 好吧,下面的代码片段满足了您的需求,尽管我认为这不是您所需要的。 MS Word is NOT a browser, I'm not sure if it supports all the styles or if jQuery works there... 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM