解释:
可以把这个代码和“http://mp.blog.csdn.net/postedit/78954570”的ES3写法进行对比,你会发现,ES3和ES6只是写法不同,核心逻辑都是一样的,所以说,ES6只是个语法糖
效果图:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin:0;
padding:0;
list-style: none
}
#ball1{
position:absolute;
left:10px;
top:10px;
width:50px;
height:50px;
border-radius:50%;
background-color:pink;
}
#ball2{
position:absolute;
left:200px;
top:10px;
width:30px;
height:30px;
border-radius:50%;
background-color:green;
}
#ball3{
position:absolute;
left:500px;
top:10px;
width:80px;
height:80px;
border-radius:50%;
background-color:red;
}
</style>
</head>
<body style="height:1000px;">
<input id="btn" type="button" value="动起来" />
<div id="ball1">
</div>
<div id="ball2">
</div>
<div id="ball3">
</div>
</body>
</html>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
//1、定义类(型)
class Ball{
constructor(domObj,width,height,bgColor,left,top,leftInc,topInc,timespace,leftDirection,topDirection){
//1)、属性(有什么)
this.domObj = domObj;
//宽高
this.width = width;
this.height = height;
//颜色
this.bgColor = bgColor;
//当前位置
this.left = left;
this.top = top;
//速度(增量和时间间隔)
this.leftInc = leftInc;//增量没有正负
this.topInc = topInc;
this.timespace = timespace;
//方向
this.leftDirection = leftDirection;
this.topDirection = topDirection;
//定时器;
this.myTimer = null;
}
//2)、方法(能干什么)
//走
go(){
this.myTimer = setInterval(()=>{
//1、改变球球的当前位置:left和top的值(javascript中的数据);
this.left= this.left+this.leftInc*this.leftDirection;
this.top = this.top+this.topInc*this.topDirection;
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
let clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
//2、left和top的合法性判断(判断边缘);
if(this.left-scrollLeft<=0){
//this.leftInc = Math.abs(this.leftInc);
//碰到左边缘时,改变方向
this.leftDirection = 1;
//}else if(top-横向滚动掉的距离>可视区域的宽度-球球的宽度){
}else if(this.left-scrollLeft>clientWidth-this.domObj.offsetWidth){
//碰到右边缘时,改变方向
this.leftDirection = -1;
}
if(this.top-scrollTop<=0){
this.topDirection = 1;
//}else if(top-纵向滚动掉的距离>可视区域的高度-球球的高度){
}else if(this.top-scrollTop>clientHeight-this.domObj.offsetHeight){
this.topDirection = -1;
}
//3、改变外观(UI)
this.domObj.style.left = this.left+"px";
this.domObj.style.top = this.top+"px";
},this.timespace);
}
}
window.onload = function(){
//domObj,width,height,bgColor,left,top,leftInc,topInc,timespace,leftDirection,topDirection
var b1 =new Ball($("ball1"),50,50,"pink",10,10,2,2,20,1,1);
b1.go();
var b2 =new Ball($("ball2"),30,30,"green",200,10,3,3,10,-1,1);
b2.go();
var b3 =new Ball($("ball3"),80,80,"red",500,10,3,3,5,1,1);
b3.go();
}
</script>