为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕姐8265434 2021-12-02 15:52:21
代码一遍又一遍地运行。我需要按钮旋转到 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>
查看完整描述

2 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

您需要首先获取元素的旋转作为变量,然后您可以像这样更改旋转方向。


if(currentrotation>=180)

    {

     rightrotation=false

    };

else if(currentrotation<=0)

    {

    rightrotation=true

    }


if(rightrotation)

   {

    i+=45;

   }

else

   {

   i-=45;

   }



要获得当前的旋转值,您需要执行一些数学函数。我发现这个网站解释了它获取 css 的旋转值

查看完整回答
反对 回复 2021-12-02
?
慕姐4208626

TA贡献1852条经验 获得超7个赞

这应该做。我们从方向开始 + 每当旋转达到 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>


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 461 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信