簡體   English   中英

如何使用 javascript 中的相同按鈕將元素旋轉到 180 度,然后再旋轉到 0 度

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

代碼一遍又一遍地運行。 我需要按鈕旋轉到 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>

將某物旋轉 180 度然后回到 0 與將其旋轉到 360 度相同,對嗎? 如果可以一直增加 180,為什么還要將其旋轉回 0?

這應該這樣做。 我們從方向開始 + 每當旋轉達到 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>

您需要首先獲取元素的旋轉,作為變量,然后您可以改變旋轉方向,例如像這樣。

if(currentrotation>=180)
    {
     rightrotation=false
    };
else if(currentrotation<=0)
    {
    rightrotation=true
    }

if(rightrotation)
   {
    i+=45;
   }
else
   {
   i-=45;
   }


要獲得當前的旋轉值,您需要執行一些數學函數。 我找到了解釋它的網站Get Rotation value of css

編輯:@Frank Castle 已經發布了更好的解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM