我有两个div(即div1和div2),div1逆时针旋转,div2顺时针旋转。现在我希望两个div连续每5秒后改变它们的旋转方向,就像div1逆时针旋转5秒后顺时针旋转然后顺时针方向旋转5秒后依次旋转等等。同样的过程适用于另一个div ..
<div id="div1" style="height:100px; width:100px; border:2px solid gray">div1 </div>
<div id="div2" style="margin-top:100px; height:100px; width:100px; border:2px solid Red">div2</div>
<script>
rotate(0,0);
function rotate(degree1, degree2) {
$("#div1").css({ WebkitTransform: 'rotate(' + degree1 + 'deg)' });
$("#div2").css({ WebkitTransform: 'rotate(' + degree2 + 'deg)' });
$("#div1").css({ '-moz-transform': 'rotate(' + degree1 + 'deg)'});
$("#div2").css({ '-moz-transform': 'rotate(' + degree2 + 'deg)'});
timer = setTimeout(function () {
rotate(++degree1, --degree2);
}, 5);
}
</script>
答案 0 :(得分:4)
如果我理解你的问题,这是你需要的代码(这里是sample fiddle):
var invert = false;
startRotating();
function startRotating() {
rotate(0, 0);
setTimeout(invertRotate, 5000);
}
function invertRotate() {
invert = !invert;
setTimeout(invertRotate, 5000);
}
function rotate(degree1, degree2) {
$("#div1").css({
WebkitTransform: 'rotate(' + degree1 + 'deg)'
});
$("#div2").css({
WebkitTransform: 'rotate(' + degree2 + 'deg)'
});
$("#div1").css({
'-moz-transform': 'rotate(' + degree1 + 'deg)'
});
$("#div2").css({
'-moz-transform': 'rotate(' + degree2 + 'deg)'
});
setTimeout(function () {
invert ? rotate(++degree1, --degree2) : rotate(--degree1, ++degree2);
}, 5);
}
答案 1 :(得分:0)
<div id="div1" style="height:100px; width:100px; border:2px solid gray">div1 </div>
<div id="div2" style="margin-top:100px; height:100px; width:100px; border:2px solid Red">div2</div>
<script>
rotate(0,0,0);
function rotate(degree1, degree2, timepassed) {
$("#div1").css({ WebkitTransform: 'rotate(' + degree1 + 'deg)' });
$("#div2").css({ WebkitTransform: 'rotate(' + degree2 + 'deg)' });
$("#div1").css({ '-moz-transform': 'rotate(' + degree1 + 'deg)'});
$("#div2").css({ '-moz-transform': 'rotate(' + degree2 + 'deg)'});
var orientation = 1 - (Math.round(timepassed/5000)%2)*2;
setTimeout(function () {
rotate(degree1 + orientation, degree2 - orientation, timepassed+5);
}, 5);
}
</script>
你必须通过时间。另一种方法是从起始点计算它。
答案 2 :(得分:0)
var counter = 0; var reverse = false;
rotate(0,0);
function rotate(degree1, degree2) {
$("#div1").css({ WebkitTransform: 'rotate(' + degree1 + 'deg)' });
$("#div2").css({ WebkitTransform: 'rotate(' + degree2 + 'deg)' });
$("#div1").css({ '-moz-transform': 'rotate(' + degree1 + 'deg)'});
$("#div2").css({ '-moz-transform': 'rotate(' + degree2 + 'deg)'});
timer = setTimeout(function () {
counter += 5;
if (counter == 5000) { counter = 0; reverse = reverse ? false : true;}
if (reverse) rotate(--degree1, ++degree2);
else rotate(++degree1, --degree2);
}, 5);
}
使用全局计数器和布尔。当计数器达到时间目标时,切换bool。根据bool值调用你的旋转函数。