记得给div加上绝对定位 要不然走不了
<style> * { margin: 0; padding: 0; } div { width: 200px; height: 200px; background-color: red; margin-top: 20px; position: absolute; } </style> </head> <body> <input type="button" value="移动到400px" id="btn1"> <div id="dv"></div> <script src="common.js"></script> <script> my$("btn1").onclick = function () { var json ={ width:500, height:400, top:80, left:400 }; animate(my$("dv"),json,function () { var json2 = {width:50, height:40, top:800, left:40}; animate(my$("dv"),json2,function () { var json3 ={width:600, height:600, top:80, left:600}; animate(my$("dv"),json3); }) }); }; //匀速动画封装函数 //element----元素 //attr----属性名字 //target------目标位置 function animate(element,json,fn) { clearInterval(element.timeId); element.timeId = setInterval(function () { var flag =true; for (var attr in json) { var current = parseInt(getStyle(element, attr)); var target = json[attr]; var step = (target - current) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); current += step; element.style[attr] = current + "px"; if (current!=target){ flag=false; } } if (current == target) { clearInterval(element.timeId); //所有的属性到达目标才能使用这个函数,前提是用户传入了这个函数 if (fn){ fn(); } } //测试代码 console.log("目标位置:"+target+",当前位置:"+current+",每次移动的步数"+step+"") }, 20); } //获取计算后属性值函数----任意一个元素的一个属性值 function getStyle( elemtnt,attr) { return window.getComputedStyle?window.getComputedStyle(elemtnt,null)[attr]:elemtnt.currentStyle[attr]; }
本文介绍了一种利用CSS样式和JavaScript实现元素动画效果的方法。通过设置div元素的绝对定位并结合JavaScript定时器逐步更新元素的位置和尺寸,实现了平滑过渡效果。文中详细解释了动画实现的具体步骤及核心代码。
991

被折叠的 条评论
为什么被折叠?



