我需要有几个 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 更改为类),但最初的独立性问题仍然存在。
最佳答案
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>
关于javascript - 使用 Javascript 的几个旋转 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38761725/