jquery图片旋转
以下是使用jQuery实现图片旋转的几种方法,包括CSS动画和JavaScript控制:
使用CSS动画实现旋转
通过添加/移除CSS类实现旋转效果,性能较好:
// CSS定义旋转动画
.rotate {
animation: spin 2s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
// jQuery控制
$('#image').click(function() {
$(this).toggleClass('rotate');
});
使用jQuery动画旋转
通过动态修改transform属性实现逐步旋转:
let angle = 0;
$('#rotate-btn').click(function() {
angle += 90;
$('#image').css('transform', 'rotate(' + angle + 'deg)');
});
实现连续旋转动画
结合jQuery的animate()和step函数实现平滑旋转:
$('#image').hover(
function() {
$(this).stop().animate(
{ deg: 360 },
{
duration: 2000,
step: function(now) {
$(this).css('transform', 'rotate(' + now + 'deg)');
}
}
);
},
function() {
$(this).stop();
}
);
拖拽旋转实现
结合mousemove事件实现拖拽旋转效果:

let isDragging = false;
let startAngle = 0;
let currentAngle = 0;
$('#image').mousedown(function(e) {
isDragging = true;
startAngle = getAngle(e.pageX, e.pageY);
});
$(document).mousemove(function(e) {
if (!isDragging) return;
const newAngle = getAngle(e.pageX, e.pageY);
currentAngle += newAngle - startAngle;
startAngle = newAngle;
$('#image').css('transform', 'rotate(' + currentAngle + 'deg)');
});
$(document).mouseup(function() {
isDragging = false;
});
function getAngle(x, y) {
const rect = $('#image')[0].getBoundingClientRect();
const centerX = rect.left + rect.width/2;
const centerY = rect.top + rect.height/2;
return Math.atan2(y - centerY, x - centerX) * 180 / Math.PI;
}
注意事项
- 现代浏览器推荐使用CSS transforms代替jQuery animate以获得更好性能
- 对于复杂旋转动画,建议使用GSAP等专业动画库
- 旋转时注意设置transform-origin属性控制旋转中心点
- 考虑添加will-change: transform提升动画性能






