所以我想转换这段代码:
$('.spawn_worm').animate({
left: '+=20px',
top: '-=20px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=16px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=12px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=8px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=4px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=0px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=4px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=8px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=8px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=12px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=16px'
},100, "linear", function(){
});
});
});
});
});
});
});
});
});
});
});做一些不那么愚蠢的事。因为这需要我花一年的时间来完成,而且因为它有很多代码,所以我认为可以用循环来解决它。
我希望动画函数属性left总是相同的+=20px。属性top在-20px中开始并增加到180px,然后再次减少到180px并在(window.width)/20循环后完成。
这是可能的吗?感谢并抱歉提出了新手问题(:
发布于 2016-04-21 13:16:00
你可以使用类似这样的东西。根据需要更改if条件。
var count = parseInt(window.innerWidth/20);
function animateElement(){
if(count){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=20px'
}, 100, animateElement);
count--;
}
}
animateElement();发布于 2016-04-21 14:05:32
您可以使用像这样的循环
jQuery(function($) {
$('button').click(function() {
var top = 20,
sign = -1;
anim();
function anim() {
$('.spawn_worm').animate({
left: '+=20px',
top: (sign == 1 ? '+' : '-') + '=' + top + 'px'
}, 100, "linear", function() {
if (sign * top < 16) {
top += 2 * sign;
if (!top) {
sign = 1;
}
anim();
}
});
}
});
});body {
height: 1000px;
margin-top: 200px;
}
.ct {
position: relative;
height: 500px;
}
.spawn_worm {
height: 50px;
position: absolute;
background-color: red;
display: inline-block;
width: 50px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Test</button>
<div class="ct">
<div class="spawn_worm"></div>
</div>
https://stackoverflow.com/questions/36760016
复制相似问题