我想要一个“命运之轮”效果。当用户单击图像时,它会从最后一个位置旋转随机度数(180-540 度之间)。旋转应使用 CSS3 完成。到目前为止,这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#pic {
position: absolute;
top: 200px;
left: 200px;
}
@-webkit-keyframes spin
{
100% {-webkit-transform: rotateZ(300deg);}
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function animRes() {
var $element = $("#pic").bind("webkitAnimationEnd", function(){
this.style.webkitAnimationName = "";
});
}
function doSpin() {
animRes();
$("#pic").css('-webkit-animation', 'spin 1s ease-out');
$("#pic").css('-webkit-animation-fill-mode', 'forwards'); //doesn't work when using AnimRes()
}
</script>
</head>
<body>
<img id="pic" src="picture.jpg" alt="pic" onclick="doSpin();"/>
</body>
</html>
问题是:
如何随机改变关键帧的旋转值?
如何从上一个位置继续旋转?
目前 animRes() 正在重置动画,因此 -webkit-animation-fill-mode: forwards
不起作用,但没有 animRes() 我无法重置动画以获得更多旋转.非常感谢使用 jQuery 和纯 JS 编写答案。
最佳答案
你需要了解一些数学知识才能实现你想做的事情,希望它不会太难理解......
var degrees=0, seconds=0, previousRotation=0;
$("#spinner").click(function(){
previousRotation = degrees;
degrees+= parseInt(Math.random() * 360 + 180);
//you should adjust this formula
miliseconds = parseInt((degrees - previousRotation)) * 5;
$(this).css({
"-webkit-transform" : "rotate("+ degrees +"deg)",
"-webkit-transition-duration" : miliseconds + "ms"
});
});
我使用 CSS Transitions 而不是动画,因为它们更简单。
如果要转换的度数更多,则 miliseconds = ... 公式会使转换持续更长时间。希望您可以将所有这些集成到您已经编写的代码中。
您可以在此处查看演示:http://jsfiddle.net/XkNrf/
关于javascript - 使用CSS3从最后一个位置随机旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7242046/