每次点击都要将div旋转45度。它按预期工作正常。我在这个页面中有3个'.expand-btn'类名。会发生什么,点击它会触发所有'.expand-btn'。
我想只触发'expand-btn'。不是其他人。
JS:
var _rotation = 0;
$.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
};
$('.expand-btn').click(function() {
_rotation += 45;
$(this).rotate(_rotation);
});
HTML:
<div class="expand-btn" id="test1">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
<div class="expand-btn" id="test2">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
<div class="expand-btn" id="test3">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
答案 0 :(得分:2)
您需要为每个对象分别存储旋转值。你可以,例如请使用jQuery.data()
:
$.fn.rotate = function(delta) {
// get the current stored rotation, or 0 if none was currently stored
var degrees = $(this).data().rotation || 0;
// add the delta to this value
degrees += delta;
// store the new value with the object
$(this).data().rotation = degrees;
// set the transformation
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
};
$('.expand-btn').click(function() {
$(this).rotate(45);
});
要正确扩展jQuery集,您应该迭代集合的元素并为每个单独的代码应用代码。现在编写$.fn.rotate
的方式将根据第一个元素的值设置集合中所有元素的旋转。
或解析当前transform
以检索该实际值。
答案 1 :(得分:0)
您可以将数据属性添加到div,您可以在其中存储当前角度。
HTML:
<div class="expand-btn" id="test1" data-degrees="0">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
<div class="expand-btn" id="test2" data-degrees="0">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
<div class="expand-btn" id="test3" data-degrees="0">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
JS:
$(document).ready(function(){
$('.expand-btn').click(function() {
var currentDegrees = $(this).data("degrees");
currentDegrees += 15;
$(this).css({'transform' : 'rotate(' + currentDegrees + 'deg)'});
var currentDegrees = $(this).data("degrees", currentDegrees);
});
});