<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 10px;
top: 50px;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script>
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var box = document.getElementById("box");
btn200.onclick = function () {
animate(box,"width",200);
}
btn400.onclick = function () {
animate(box,"height",400);
}
function animate(obj,attr,target){ //参数1:对象 参数2:属性 参数3:目的
//盒子本身位置+步长
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var current =parseInt(getStyle(obj,attr)); //得到当前的样式,结果是带单位的,要用parseInt
var step = (target - current)/10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style[attr] = current + step + "px";
if(current == target){
clearInterval(obj.timer);
}
},30);
}
function getStyle(obj,attr){
if(obj.currentStyle){ //ie
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,null)[attr]; // w3c
}
}
</script>
tx4-封装运动框架基本函数(单个属性)
最新推荐文章于 2025-10-29 20:47:35 发布
本文介绍了一个使用CSS样式和JavaScript实现的简单动画案例。通过按钮点击改变元素宽度和高度,实现了平滑过渡效果。文章提供了完整的HTML、CSS及JavaScript代码。
740

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



