自定義動畫方法animate()

榴蓮餅發表於2017-03-27

1.自定義簡單動畫

animate()方法可以使元素動起來,而且animate()方法更具有靈活性.通過animate()方法,能夠實現更加精細新穎的動畫效果;使用animate()方法之前,為了能影響該元素的"top","left","bottom"和"right"樣式屬性,必須把元素的position樣式設定為"relative"或者"absolut"

<style type="text/css">
*{margin:0;padding:0;}	
body { padding: 60px }
#panel {position: relative; width: 100px; height:100px;border: 1px solid #0050D0;background: #96E555; cursor: pointer}
</style>
<script type="text/javascript">
$(function(){
//      $("#panel").click(function(){
//	   $(this).animate({left: "500px"}, 3000);
//	})      
   $("#panel").toggle(function(){
	    $(this).animate({left: "500px"}, 3000);
	},function(){
	    $(this).animate({top:"200px"}, 3000);
	})
})
</script>
</head>
<body>
<div id="panel"></div>
</body>

2.累加,累減動畫

在之前的程式碼中,設定了{left:"500px"}作為動作引數.如果在500px之前加上"+="或者"-="符號表示在當前位置累加或者累減

3.多重動畫

(1)同時執行多個動畫

如果需要向右滑動的同時放大元素的高度.{left:"500px",height:"200px"}

<style type="text/css">
*{margin:0;padding:0;}	
body { padding: 60px }
#panel {position: relative; width: 100px; height:100px;border: 1px solid #0050D0;background: #96E555; cursor: pointer}
</style>
<script type="text/javascript">
$(function(){
    $("#panel").click(function(){
	    $(this).animate({left: "500px",height:"200px"}, 3000);
	})
})
</script>
</head>
<body>
<div id="panel"></div>
</body>

(2)按順序執行多個動畫

上面的是同時進行的,如果需要先向左移動然後再放大高度,按順序寫入程式碼就可以了$(this).animate({left:"500px"},3000);$(this).animate({height:"500px"},3000);或者直接串聯$(this).animate({left:"500px"},3000).animate({height:"500px"},3000);這個稱為動畫佇列

<style type="text/css">
*{margin:0;padding:0;}    
body { padding: 60px }
#panel {position: relative; width: 100px; height:100px;border: 1px solid #0050D0;background: #96E555; cursor: pointer}
</style>
<script type="text/javascript">
$(function(){
    $("#panel").click(function(){
         $(this).animate({left: "500px"}, 3000)
                .animate({height: "200px"}, 3000);
    })
})
</script>
</head>
<body>
<div id="panel"></div>
</body>

4.綜合動畫

單機div元素讓它向右移動的同時增大它的高度,並將它們的不透明度從50%變換為100%,然後再讓它從上到下移動,同時它的寬度變大,當完成這些效果後,淡出方式隱藏

<style type="text/css">
*{margin:0;padding:0;}	
body { padding: 60px }
#panel {position: relative; width: 100px; height:100px;border: 1px solid #0050D0;background: #96E555; cursor: pointer}
</style>
<script type="text/javascript">
    $(function(){
        $("#panel").css("opacity", "0.5");
        $("#panel").click(function(){
              $(this).animate({left: "400px", height:"200px" ,opacity: "1"}, 3000)
					 .animate({top: "200px" , width :"200px"}, 3000 )
					 .fadeOut("slow");
        });
    });
</script>
</head>
<body>
<div id="panel"></div>
</body>


相關文章