简体   繁体   English

如何使用 javascript 中的相同按钮将元素旋转到 180 度,然后再旋转到 0 度

[英]How can I rotate an element to 180deg the back to 0deg using the same button in javascript

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我需要按钮旋转到 180 然后再回到 0deg 然后再到 180 递增和递减 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?将某物旋转 180 度然后回到 0 与将其旋转到 360 度相同,对吗? Why would you need to rotate it back to 0 if you can just keep increasing by 180?如果可以一直增加 180,为什么还要将其旋转回 0?

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我们从方向开始 + 每当旋转达到 180 时,将方向更改为 - 每当旋转达到 0 时,将方向更改回 + 我们在 i 变量中跟踪旋转

 <: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我找到了解释它的网站Get Rotation value of css

EDIT: @Frank Castle already posted better solution编辑:@Frank Castle 已经发布了更好的解决方案

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

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