【问题标题】:Several rotating divs using Javascript使用 Javascript 的几个旋转 div
【发布时间】:2016-08-04 08:03:19
【问题描述】:

我需要几个 div,每个 div 都应该能够通过鼠标单击独立地在四个(!)方向上旋转。

从这个问题(和其他一些问题)中,我找到了非常合适的方式来在 4 个方向上旋转(不是两个方向,这更容易) Rotate a div using javascript,这里是fiddle

JS:

$(document).ready(function() {
  var degree = 0; //Current rotation angle, 0->0, 1->90, 2->180, 3->270
  $('.rotating').click(function() {
    $(this).toggleClass('rotated' + degree.toString()); //Disable previous rotation
    degree = (degree + 1) % 4;
    $(this).toggleClass('rotated' + degree.toString()); //Add new rotation
  });
});

但它只适用于一个旋转元素。一旦我添加了第二个 div,它就会按预期停止工作(旋转不是独立的,请尝试先单击“A”,然后单击“B”)

<div class="rotating rotated0">A</div>
<div class="rotating rotated0">B</div>

我认为,根本原因是因为我使用了一个“度”变量,并且它在我的 div 之间共享。那么问题来了——如何实现多个可以独立旋转的 div?


我已经根据第一个答案更新了代码(将 id 更改为 class),但最初的独立性问题仍然存在。

【问题讨论】:

    标签: javascript jquery html css rotation


    【解决方案1】:

    id 属性必须只有一个。将id 改成类。

    更新

    这是最终代码:

    $(document).ready(function() {
       
      $('.rotating').click(function() {
        var currentDeg   =  $(this).attr("data-deg");
      
        $(this).css({ '-moz-transform': 'rotate(' + currentDeg + 'deg)'});
        $(this).css({ WebkitTransform: 'rotate(' + currentDeg + 'deg)'});
        
        currentDeg = eval(currentDeg)+eval(90);
        
        $(this).attr("data-deg", currentDeg.toString());
        
        //restore
        if(currentDeg > 270){
          $(this).attr("data-deg", "0");
        }
        
      });
    });
    .rotating {
      width: 20px;
      height: 20px;
      background-color: red;
      margin-top: 0px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="rotating" data-deg="90">A</div>
    <div class="rotating" data-deg="90">A</div>

    【讨论】:

    • 谢谢,我还在 div 'class="rotating rotate0"' 中添加了初始旋转。但是经过几次尝试,我发现点击似乎仍然不是独立的。单击第一个 div,然后单击第二个 div。预期行为 - 两者都应旋转 90 度。实际 - 秒旋转了 180。
    • 已更新。删除重复行$(this).toggleClass('rotated' + degree.toString());
    • 它不是重复的,它正在禁用以前的转换..没有它它就不起作用(尝试循环旋转4次以上)
    • 太好了,这正是我需要的!谢谢!
    【解决方案2】:

    您的代码已修复。

        $(document).ready(function() {
          var degree = 0; //Current rotation angle, 0->0, 1->90, 2->180, 3->270
          $('.rotating').click(function() {
            $(this).toggleClass('rotated' + degree.toString()); //Disable previous rotation
            degree = (degree + 1) % 4;
            $(this).toggleClass('rotated' + degree.toString()); //Add new rotation
          });
        });
    

    标记:

    <div class="rotating">A</div>
    <div class="rotating">B</div>
    

    【讨论】:

    • 看起来更好,但点击仍然不是独立的(参见 Dave 的示例)。有什么想法吗?
    • 啊,是的。 @TheGodfather如果你希望你的点击是独立的,你需要将$('.rotating')替换为$(this) **但保持$('.rotating').click不变
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多