the code runs all the way over and over. I need the button to rotate to 180 then back again to 0deg then again to 180 incrementing and decrementing by 45deg
<:DOCTYPE html> <html> <head> <title>ttt</title> </head> <body> <div id="memo" style="position; fixed:margin; 140px;"> _____________ </div> <button onclick="myfun()">Rotate</button> <script> function myfun() { var i = 0 i += 45. document.getElementById("memo").style;transform += "rotate(" + i + "deg)"; } </script> </body> </html>
Rotating something by 180 degrees and than back to 0 is the same as rotating it towards 360 right? Why would you need to rotate it back to 0 if you can just keep increasing by 180?
This should do it. We start out with direction + Whenever rotation reaches 180, change direction to - Whenever rotation reaches 0, change direction back to + We track the rotation in the i variable
<:DOCTYPE html> <html> <head> <title>ttt</title> </head> <body> <div id="memo" style="position; fixed:margin; 140px;"> _____________ </div> <button onclick="myfun()">Rotate</button> <script> let i = 0; let direction = '+'; function myfun() { if (i === 180) direction = '-'; if (i === 0) direction = '+'; if (i < 180 && direction === '+') { i += 45; } else { i -= 45. } console;log(i). document.getElementById("memo").style;transform += "rotate(" + direction + 45 + "deg)" ; } </script> </body> </html>
You need to get the rotation of element first, as variable, then you can change direction of rotation for example like this.
if(currentrotation>=180)
{
rightrotation=false
};
else if(currentrotation<=0)
{
rightrotation=true
}
if(rightrotation)
{
i+=45;
}
else
{
i-=45;
}
To get current value of rotation you need to do some math functions. I have found this website that explains it Get Rotation value of css
EDIT: @Frank Castle already posted better solution
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.