如何在CSS中使用Javascript变量?

时间:2018-03-21 09:27:48

标签: javascript jquery html css

我点击它时试图让图像旋转。你点击的次数越多,旋转的速度就越快,如果你停止点击,它会随着时间的推移而减慢。

问题是没有jQuery旋转对象的唯一方法是使用"转换" CSS中的属性(我至少知道)。有没有办法在CSS中使用JavaScript变量?还是有另一种方式来旋转我的形象?或者我需要使用jQuery吗?

代码:



var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;

//Activates Slowdown
window.onload = loop();

//Speed up
function spin() {
  if (speed < 0) {
    speed = speed + 10;
    loop()
  } else {
  speed = speed + 10;
  }
}

spinner.addEventListener('click', spin);

//Slowdown
function loop() {
  setTimeout(
    function slow() {
      speed = speed - slowSpeed;
      document.getElementById("speed").innerHTML = speed;
      if (speed > 0) {
        loop();
      }
    }, 1000)
}

//Selectors
function wheel() {
  spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
  spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}
&#13;
#spinner {
  width: 500px;
}
#spinner {
  transform: rotate("speed"deg);
}
/* The "speed" is the variable I want to use from the JavaScript */ 
&#13;
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css"/>
  </head>
  <body>
    <div id="spinnerContainer">
      <img id="spinner" src="http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png"/>
      <h4 id="speed">N/A</h4>
    </div>
    <div id="selectors">
      <ul>
        <button onclick="wheel()">Wheel</button>
        <button onclick="spiral()">Spiral</button>
      </ul>
    </div>
    <footer>

    </footer>
    <script src="script.js"></script>
  </body>
</html>
<!-- END -->
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:6)

您可以在css中声明变量(请参阅规范 - &gt; https://www.w3.org/TR/css-variables/

:root {
  --deg: 10deg;
}

然后你可以使用它

#spinner {
  transform: rotate( var(--deg));
}

如何使用JavaScript访问变量

获取

var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var deg= rootStyles.getPropertyValue('--deg');
console.log(deg); 
--> 10deg

设置

root.style.setProperty('--deg', '20deg');

目前,全球网站流量的88%supports CSS Variables

答案 1 :(得分:4)

不,你不能在css中使用javascript变量,但你可以通过javascript的DOM元素,style属性动态地改变元素的样式。

document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";

在你的情况下:

var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;

//Activates Slowdown
window.onload = loop();

//Speed up
function spin() {
  if (speed < 0) {
    speed = speed + 10;
    loop()
  } else {
  speed = speed + 10;
  }
}

spinner.addEventListener('click', spin);

//Slowdown
function loop() {
  setTimeout(
    function slow() {
      speed = speed - slowSpeed;
      document.getElementById("speed").innerHTML = speed;
      if (speed > 0) {
        loop();
      }

      document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";

    }, 1000)
}

//Selectors
function wheel() {
  spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
  spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}

修改

根据Vladu Ionut's answer,我们可以在CSS中使用变量。 优点:

  1. 适用于现代浏览器。
  2. Disadavantage:

    1. 它在以下旧浏览器中不起作用:
      1. IE
      2. EDGE&lt; = 15
      3. Chrome&lt; 49等 ... ...
    2. 编辑:2,根据评论更新代码

                  var spinnerImg   = undefined;
                  var speedTxt     = undefined;
                  var wheelImgUrl  = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
                  var spiralImgUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
       
                  var speed           = 0;
                  var maxSpeedChange  = 10;
                  var slowSpeed       = 2;
                  var speedParam      = slowSpeed;
      
                  /**
                  * Function to change the image to wheel
                  *
                  * @Arguments: none
                  *
                  * @Returns: void
                  */
                  function changeToWheel() {
                      spinnerImg.src = wheelImgUrl;
                  }
      
                  /**
                  * Function to change the image to spiral
                  *
                  * @Arguments: none
                  *
                  * @Returns: void
                  */
                  function changeToSpiral() {
                      spinnerImg.src = spiralImgUrl;
                  }
      
                  /**
                  * Function to update speed display
                  *
                  * @Arguments: void
                  *
                  * @Returns: void
                  */
                  function updateSpeedTxt() {
                      speedTxt.innerHTML = speed;
                  }
      
                  /**
                  * @Function to rotate the image
                  *
                  * @Arguments: void
                  *
                  * @Returns: void
                  */
                  function rotateImg() {
                      spinnerImg.style.transform = "rotate(" + speed + "deg)";
                  }
      
                  window.addEventListener("load", function() {
                      spinnerImg = document.getElementById("spinner");
                      speedTxt   = document.getElementById("speed");
                      speed = speedParam;
                      setInterval(function() {
                          updateSpeedTxt();
                          rotateImg();
                          if (speedParam > slowSpeed) {
                              speedParam -= 0.05;
                          }
                          if (speedParam < slowSpeed) {
                              speedParam = slowSpeed;
                          } 
                          speed += speedParam;
                      }, 50); 
      
      
                      spinnerImg.addEventListener("click", function() {
                          speedParam += maxSpeedChange; 
                      });
      
                  }); 
                  #spinner {
                      width: 500px;
                      transform-origin: center;
                  } 
      <!DOCTYPE html>
      <html>
          <head> 
          </head>
          <body>
              <div id="spinnerContainer">
                  <img id="spinner" src="http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png"/>
                  <h4 id="speed">N/A</h4>
              </div>
              <div id="selectors">
                  <ul>
                      <button onclick="changeToWheel()">Wheel</button>
                      <button onclick="changeToSpiral()">Spiral</button>
                  </ul>
              </div>
              <footer>
      
              </footer> 
          </body>
      </html>

答案 2 :(得分:1)

答案是否定的。你不能在css中使用javascript变量。但是你可以使用javascript来应用css样式。这是您的问题的解决方案

&#13;
&#13;
var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;

//Activates Slowdown
window.onload = loop();

//Speed up
function spin() {
  if (speed < 0) {
    speed = speed + 10;
    loop()
  } else {
  speed = speed + 10;
  }
    document.getElementById("spinner").style.transform = "rotate(" + speed + "deg)";

}

spinner.addEventListener('click', spin);

//Slowdown
function loop() {
  setTimeout(
    function slow() {
      speed = speed - slowSpeed;
      document.getElementById("speed").innerHTML = speed;
      if (speed > 0) {
        loop();
      }
    }, 1000)
}

//Selectors
function wheel() {
  spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
  spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}
&#13;
#spinner {
  width: 500px;
}
#spinner {
  transform: rotate(90deg);
}
/* The "speed" is the variable I want to use from the JavaScript */
&#13;
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css"/>
  </head>
  <body>
    <div id="spinnerContainer">
      <img id="spinner" src="http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png"/>
      <h4 id="speed">N/A</h4>
    </div>
    <div id="selectors">
      <ul>
        <button onclick="wheel()">Wheel</button>
        <button onclick="spiral()">Spiral</button>
      </ul>
    </div>
    <footer>

    </footer>
    <script src="script.js"></script>
  </body>
</html>
<!-- END -->
&#13;
&#13;
&#13;

答案 3 :(得分:0)

如果你想减少样板,可以使用sass mixin为你生成所有速度等级;

&#13;
&#13;
var box = document.getElementById('box');
var speed = 0;
var countdown;
box.addEventListener('click', function(e) {
  if(speed === 3) return;
  speed++;
  box.className = "box-"+speed;
  clearInterval(countdown);
})

box.addEventListener('mouseout', function(e) {
  countdown = setInterval(function(){ 
    if(speed === 0) {
      clearInterval(countdown);
    } else {
      speed --;
      box.className = "box-"+speed;
    }
  }, 2000);
})
&#13;
#box {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  top: 250px;
  left: 250px;
}

#box:hover{
  cursor: pointer;
}

.box-1 {
		-webkit-animation: rotation 3s infinite linear;
}

.box-2 {
		-webkit-animation: rotation 2s infinite linear;
}

.box-3 {
		-webkit-animation: rotation 1s infinite linear;
}


@-webkit-keyframes rotation {
		from {
				-webkit-transform: rotate(0deg);
		}
		to {
				-webkit-transform: rotate(359deg);
		}
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>spin box animation</title>
</head>
<body>
  <div id="box"></div>
</body>
</html>
&#13;
&#13;
&#13;