jQuery多模块独立旋转问题:全局变量导致旋转角度相互干扰
解决多个区块独立旋转的全局变量冲突问题
嘿,这个问题我太熟悉了——全局变量共享状态就是这类场景的典型坑!你猜的没错,问题确实出在那个全局的rotation变量上:所有.strijela元素都共用同一个变量,每次点击不管哪个区块,这个值都会累加,导致新点击的区块直接继承了之前所有点击的总角度,自然就乱了。
解决方案:给每个元素单独存储旋转状态
我们可以用jQuery的data()方法,给每个区块元素单独保存它自己的旋转角度,这样每个元素的状态都是独立的,不会互相干扰。
修改后的完整代码如下:
<!DOCTYPE html> <html> <head> <style> .strijela { transition: 0.3s linear; background-color: black; color: white; height: 150px; width: 150px; margin: 20px auto; display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="strijela">区块1</div> <div class="strijela">区块2</div> <div class="strijela">区块3</div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> jQuery.fn.rotate = function(degrees) { $(this).css({ 'transform': 'rotate(' + degrees + 'deg)' }); }; $('.strijela').click(function() { // 获取当前元素的已旋转角度,默认0(第一次点击时) let currentRotation = $(this).data('rotation') || 0; // 累加180度 currentRotation += 180; // 把更新后的角度存回元素的data属性里 $(this).data('rotation', currentRotation); // 执行旋转 $(this).rotate(currentRotation); }); </script> </body> </html>
关键改动说明:
- 移除了全局的
rotation变量,转而用$(this).data('rotation')来存储每个元素独有的旋转角度 - 每次点击时,先获取当前元素自己的旋转值(第一次点击时因为没有这个数据,所以用
|| 0取默认值0) - 累加180度后,再把新角度存回元素的data属性,确保下次点击时能拿到正确的当前值
这样每个区块的旋转状态都是独立的,点击哪个就只会更新哪个的角度,完全不会影响其他区块啦!
内容的提问来源于stack exchange,提问作者HovSky
相关产品推荐
相关产品推荐

