简体   繁体   中英

JS style webkit transform not appearing in inline style

When setting multiple transform properties on DOM element style, the browser is not showing all set properties (both -webkit-, ms, and regular) - for example :

element.style.tranform = 'rotate(90deg)';
element.style.webkitTranform = 'rotate(90deg)';
element.style.msTranform = 'rotate(90deg)';

will produce the following inline style attribute

<div style="transform:rotate(90deg)" ></div>;

This means that the browser is not settings ALL of the properties, instead it is taking only one of them.

This is a problem, because we have to send the HTML as is to the server side in order to produce PDF. so, instead we have found a workaround which works (kind of) - using element.setAttribute('style','transform...-webkit- etc...');

The above approach works, but we have to reconstruct the style attribute each time, and the transform must be applied only AFTER all of the other properties have been set, which is not so elegant.

Does anyone knows how to work around this?

Thanks in advance!

I think you've already found your workaround: Using setAttribute . It's not pretty, but with prefixed properties, you can't trust the HTML from browser X will work in browser Y, since there's no reason browser X would include invalid (from its perspective) properties when generating the text for the style attribute's value.

With your workaround, you'll need to be careful of at least two things:

  1. That you test carefully in your target browsers. I think all browsers faithfully retain what you set with setAttribute (subject to #2 below), but...test. :-)

  2. Be sure nothing in your code sets a style via the style object after you've done the setAttribute thing, since that will make the browser drop the (from its perspective) invalid style text. For instance, on Chrome, Firefox, Edge and Safari (at least), the following drops the invalid foo: bar style when I set fontWeight :

 var element = document.getElementById("element"); element.setAttribute("style", "foo: bar"); console.log("before using style:", element.getAttribute("style")); element.style.fontWeight = "bold"; console.log("after using style: ", element.getAttribute("style")); 
 <div id="element"></div> 

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