运动(move)的封装

运动的封装

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#box1{width: 100px;height: 100px;position: absolute;left: 0;top:0;background: red;}
			#box2{width: 100px;height: 100px;position: absolute;left: 0;top:140px;background: blue;}
			.line{width: 1px;height: 500px;background: #000;position: absolute;left: 600px;top:0;}
		</style>
	</head>
	<body>
		 <div id="box1"></div>
		 <div id="box2"></div>
		 <div class="line"></div>
	</body>
	<script type="text/javascript">
		let obox1 = document.getElementById("box1");
		let obox2 = document.getElementById("box2");
		
		obox1.onmouseover=function(){
			move(obox1,"left",1000);
		}
		
		function move(ele,attr,target){//元素 属性 目标
			// ele是一个元素对象,对象,对象可以做什么,存储数据
			clearInterval(ele.t);
			ele.t=setInterval(()=>{
				var s=getStyle(ele,attr);// 得到带有px的字符
				var iNow=parseInt(s);// 借助parseInt的取整,得到整除部分,去掉px
				
				let speed = (target - iNow)/10;
				speed=speed < 0 ? Math.floor(speed) : Math.ceil(speed);
				if(iNow === target){
					clearInterval(t);
				}else{
					ele.style.left=iNow+10+"px";
				}
			},30);
		}
		
		  // 获取非行内样式的兼容:必然会得到当前的样式值
		    function getStyle(ele,attr){
		        if(ele.currentStyle){
		            return ele.currentStyle[attr];
		        }else{
		            return getComputedStyle(ele,false)[attr];
		        }
		    }
	</script>
</html>

发布了5 篇原创文章 · 获赞 5 · 访问量 60

猜你喜欢

转载自blog.csdn.net/zyfacd/article/details/104622260