2016-11-23 31 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

感謝您的幫助 –