简体   繁体   中英

How to rotate an image with CSS style transform by an variable of degree?

var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
console.log("hour"+h+"min"+m+"sec"+s);

document.getElementById("sec").style.transform = "rotate((s*6)deg)";

I am trying to rotate an image with ID sec by (current second*6) degree. But it seems css rotate can only take a constant degree like rotate(40deg). If I do var x =40; rotate('x'deg); var x =40; rotate('x'deg); or something like that its not going to work.

How do I let it rotate with an variable?

What you are doing is supplying a string of rotate((s*6)deg) (literally with the S*6 instead of the result) into the transform style. You need to split the string so that it concatenates the result into the string.

Use this:

ar today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
console.log("hour"+h+"min"+m+"sec"+s);

document.getElementById("sec").style.transform = "rotate(" + (s*6) + "deg)";

This will pass the value of the variable s times 6 into the string. So instead of the CSS parser questioning what the literal string s*6deg means, it will instead recieve 120deg (if the variable s were the value 20) which is a valid CSS value. It is the same concept you were using in your console.log call one line above.

You need to replace your last statement with,

document.getElementById("sec").style.transform = "rotate(("+s*6+")deg)";

Since you are passing a string instead of a value for the degree.

Hope this helps.

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