I am animating an element with the top margin. However, when said element reaches a certain margin, I want to create another event. I did what I assumed would work, but it doesnt seem to be doing anything.
So I have an element moving to margin top 300px, and when it hits 300px I want it to got to margin-top -80px.
function raindrop(element,speed) {
$(element).animate({
'margin-top':'300px'
}, speed, 'linear');
margin = parseInt($(element).css('marginTop'));
if(margin>=300) {
$(element).css('marginTop','-80px');
$(element).animate({
'margin-top':'300px'
}, speed, 'linear');
}
}
I also want to use a re-cursive function here so it keeps doing it. Any ideas what I am doing wrong?
答案 0 :(得分:1)
您的代码中不需要任何if语句来检查条件,因为if语句在动画完成之前执行。而不是if,更好地使用仅在第一个动画结束后执行的回调函数。在回调中,您可以将元素移回margin-top:-80px,一旦达到300px。如果你还想做递归,那么你可以调用你的raindrop()函数作为第二个动画的回调函数,它执行无限循环。这是修改后的代码:
<强> jQuery的:强>
$(document).ready(function(){
$("#btn").click(function(){
raindrop("#mydiv",1000);
});
});
function raindrop(element,speed) {
$(element).animate({
'margin-top':'300px'
}, speed, 'linear',function(){
margin = parseInt($(element).css('marginTop'));
//alert(margin);
$(element).animate({
'margin-top':'-80px'
}, speed, 'linear', raindrop(element, speed));
});
}
<强> CSS:强>
#mydiv
{
border:1px solid red;
width:300px;
height:150px;
}
<强> HTML:强>
<input type="button" id="btn" value="Press">
<div id="mydiv"></div>