简体   繁体   中英

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?

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. The reason I want to do this is so that MS Word (2010) will pick up the styling if I open it there

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

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...

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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