js鏈式動畫小例子

來源:互聯網
上載者:User

標籤:javascrip   瀏覽器   mouse   timer   back   html   字串   pac   com   

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>鏈式動畫</title>
<style>
* {
margin: 0;
padding: 0;
}

#odiv {
width: 100px;
height: 100px;
background: pink;
opacity: 0.5;

}
</style>
</head>

<body>
<div id="odiv">

</div>
<script type="text/javascript">
var odiv = document.getElementById("odiv");

//第三種
//執行動畫的對象,目標值,動畫的屬性,下一個動畫
odiv.onmouseover=function(){
starMove(odiv,500,‘width‘,function(){
starMove(odiv,200,‘height‘,function(){
starMove(odiv,100,‘opacity‘,function(){
console.log("結束")
})
})
})
};
odiv.onmouseout=function(){
starMove(odiv,50,‘opacity‘,function(){
starMove(odiv,100,‘height‘,function(){
starMove(odiv,100,‘width‘,function(){
console.log("結束")
})
})
})
}

function starMove(obj, targetValue, attr, nextFn) {
//執行之前動畫的結束
clearInterval(obj.timer);
obj.timer = setInterval(function(){ //執行動畫的定時器
var currentValue;//執行動畫對應的屬性的當前值
if(attr == ‘opacity‘){
currentValue=Math.round(parseFloat(getStyle(obj,attr))*100);
//
}else{
//去掉字串中的Px,再變成整數
currentValue=parseInt(getStyle(obj,attr))//100
}



var speed;//每次動畫增長的幅度
speed = (targetValue-currentValue)/4;
speed =speed>0?Math.ceil(speed):Math.floor(speed);
//當對象到達目標時,停止動畫,開始下一個動畫
if(currentValue==targetValue){
clearInterval(obj.timer);
if(nextFn){
nextFn();
}

}else{
if(attr==‘opacity‘){
obj.style.opacity=(currentValue+speed)/100;
}else{
obj.style[attr]=(currentValue+speed)+‘px‘;
}
}

}, 50);
}


//擷取當前對象元素的特性屬性的函數
function getStyle(obj,attr){
//IE8之前的瀏覽器
if(obj.currentStyle){//IE8以前的瀏覽器的方法
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}
console.log(getStyle(odiv,"height"))

</script>
</body>

</html>

js鏈式動畫小例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.