html代碼
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>css屬性運動框架</title><style>body,div{margin: 0;padding: 0;}ul,li{list-style: none;}ul li{width: 200px;height: 100px;background: yellowgreen;margin-bottom: 20px;filter:alpha(opacity:30);opacity: 0.3;border:4px solid #666666;}</style><script src="js/move.js"></script><script>window.onload=function(){var Li1=document.getElementById('li1');var Li2=document.getElementById('li2');var Li3=document.getElementById('li3');var Li4=document.getElementById('li4');var Li5=document.getElementById('li5');Li1.onmouseover=function(){startMove(this,{height:200});}Li1.onmouseout=function(){startMove(this,{height:100});}Li2.onmouseover=function(){startMove(this,{width:400});}Li2.onmouseout=function(){startMove(this,{width:200});}Li3.onmouseover=function(){startMove(this,{opacity:100});}Li3.onmouseout=function(){startMove(this,{opacity:30});}Li4.onmouseover=function(){startMove(Li4,{width:400},function(){startMove(Li4,{height:200},function(){startMove(Li4,{opacity:100},function(){});});});}Li4.onmouseout=function(){startMove(Li4,{opacity:30},function(){startMove(Li4,{height:100},function(){startMove(Li4,{width:200});});});}Li5.onmouseover=function(){startMove(Li5,{width:400,height:200,opacity:100});}Li5.onmouseout=function(){startMove(Li5,{width:200,height:100,opacity:30});} }</script></head><body><ul><li id="li1">高動畫</li><li id="li2">寬動畫</li><li id="li3">透明度動畫</li><li id='li4'>高寬透明度鏈式動畫</li><li id='li5'>高寬透明度同時動畫</li></ul></body>
</html>
引入的JS代碼,運動框架move.js
//運動
//startMove(obj,{attr1:itarget1,attr2:itarget2},fn)
function startMove(obj,json,fn) {clearInterval(obj.timer);obj.timer = setInterval(function() {var flag=true;//標桿,假設所有運動都達到了目標值for(var attr in json){//1.去當前的值var icur = 0;if(attr == 'opacity') {icur = Math.round(parseFloat(getStyle(obj,attr)) * 100); //parseFloat獲取小數.Math.round四舍五入} else {icur = parseInt(getStyle(obj, attr)); //parseInt獲取整數}//2.算速度var speed = (json[attr] - icur) / 8;speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);//3.檢測屬性動畫是否全部達到目標值if(icur !== json[attr]) {flag=false;//如果不是所有的動畫都達到目標值,標桿設為false} if(attr == 'opacity') {obj.style.filter = 'alpha(opacity:' + (icur + speed) + ')';obj.style.opacity = (icur + speed) / 100;}else {obj.style[attr] = icur + speed + 'px';}}//在動畫結束的時候檢測是否有回調函數,如果檢測到有回調函數,執行if(flag){clearInterval(obj.timer);if(fn){fn();}}}, 30)}//獲取對象屬性function getStyle(obj,attr){if(obj.currentStyle){return obj.currentStyle[attr];//IE}else{return getComputedStyle(obj,false)[attr];//火狐 chrome}}