简体   繁体   English

Javascript将转换添加为内联样式

[英]Javascript add transform as an inline style

I have a quick question: how can you add transforms as an inline style via JavaScript? 我有一个快速的问题:如何通过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: HTML:

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

JavaScript: 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 根据w3schools的说法,没有什么拼写错误,并且所有前缀都是正确的: w3schools DOM样式转换

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: 这是jQuery版本:

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

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

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