简体   繁体   中英

Javascript add transform as an inline style

I have a quick question: how can you add transforms as an inline style via JavaScript? For the last hour, I've been trying to solve this problem and also have been searching everywhere, but nothing worked. Here is my code:

HTML:

 <ul id="slider">
    <li class="slide"></li>
    <li class="slide"></li>
    <li class="slide"></li>
    <li class="slide"></li>
 </ul>

JavaScript:

 var windowWidth = $(window).width();
 var centerDistance = windowWidth / 2;
 var targets = $(".slide");
 var inlineTransform = '"' + "translateZ(" + centerDistance + "px)" + '"';
 for (var i = 0; i < targets.length; i++) {
     targets[i].style.WebkitTransform = inlineTransform;
     targets[i].style.msTransform = inlineTransform;
     targets[i].style.transform = inlineTransform;
 }

According to w3schools, nothing is spelled wrong and all the prefixes are correct: w3schools DOM style transform

The syntax should be correct too. I don't get any error messages and this code works if I use other styles.

You don't need to add additional quotes to that string. A string is a string. Quotes are only needed for string literals inside code, and you already have those.

Here's a jQuery version:

var centerDistance = $(window).width() / 2;
var t = "translateZ(" + centerDistance + "px)";
var style = {
  WebkitTransform: t,
  msTransform: t,
  transform: t
};
$(".slide").css(style);

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