如何使用jQuery旋转div

DEV*_*OPS 50 jquery

是否可以使用jQuery旋转div?我可以旋转图像,但不能旋转div; 这有什么解决方案吗?

Dan*_*ahn 79

编辑:更新为jQuery 1.8

由于将自动添加jQuery 1.8浏览器特定的转换.jsFiddle演示

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});
Run Code Online (Sandbox Code Playgroud)

编辑:添加代码使其成为一个jQuery函数.

对于那些不想再阅读的人,请你走了.有关更多详细信息和示例,请继续阅读.jsFiddle演示.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});
Run Code Online (Sandbox Code Playgroud)

编辑:这篇文章的评论之一提到了jQuery Multirotation.这个jQuery插件基本上执行上述功能,支持IE8.如果您想要最大兼容性或更多选项,可能值得使用.但是为了最小化开销,我建议使用上述功能.它适用于IE9 +,Chrome,Firefox,Opera等等.


Bobby ...这是为那些真正想在javascript中做的人.这可能是在javascript回调上旋转所必需的.

这是一个jsFiddle.

如果您想以自定义间隔旋转,可以使用jQuery手动设置css而不是添加类.喜欢这个!我在答案的底部包含了两个jQuery选项.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}
Run Code Online (Sandbox Code Playgroud)

jQuery的

确保这些包装在$(document).ready中

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});
Run Code Online (Sandbox Code Playgroud)

自定义间隔

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});
Run Code Online (Sandbox Code Playgroud)