2016-11-23 35 views
0

您好我想移动我的div当我点击一个动画效果的按钮,所以我使用。动画。但它不能正常工作 这是我使用需要移动顶部,当点击一个按钮使用动画

$(document).ready(function(){ 
 
    $("#btn1").click(function(){ 
 
     $("#box").animate({margin-Top: "300px"}); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="btn1">Animate topdown</button> 
 

 

 
<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;"></div>

什么是错在我的代码我不能用顶部,而不是边距becuse我DIV位置代码:相对;

回答

1

您需要使用marginTop或用引号包装该属性。

$(document).ready(function() { 
 
    $("#btn1").click(function() { 
 
    $("#box").animate({ 
 
     marginTop: "300px" 
 
     // or 
 
     // "margin-top" : "300px" 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="btn1">Animate topdown</button> 
 

 

 
<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;"></div>

+1

感谢。我明白 –

1

只是包装的CSS属性 '的margin-top' 用单引号或使用inbuild关键字marginTop

$(document).ready(function(){ 
 
    $("#btn1").click(function(){ 
 
     $("#box").animate({'margin-Top': "300px"}); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="btn1">Animate topdown</button> 
 

 

 
<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;"></div>

+0

没有没有要求!它也可以不用单引号 –

+0

@KarthikSivakumar - marginTop不是一个字符串,它是内置的jquery动画方法的关键变量,它不需要单引号或双引号。但是当我们尝试在css中编写属性时,我们需要将单引号或双引号添加到它。 –

+0

感谢您的帮助 –