class语法相关笔记
2018-08-24 本文已影响0人
UmustHU
用class写的一个小demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin:0;padding:0;}
.box{
position:absolute;
top:0;
width:100px;
height:100px;
background-color:cornflowerblue;
}
.left{left:0;}
.right{right:0;}
</style>
</head>
<body>
<div id="div1" class="box left"></div>
<div id="div2" class="box right"></div>
<script>
class Drag{
constructor(id){
this.oDiv = document.querySelector(id);
this.disX = 0;
this.disY = 0;
this.init()
}
init(){
this.oDiv.onmousedown = function(event){
this.disX = event.clientX - this.oDiv.offsetLeft;
this.disY = event.clientY - this.oDiv.offsetTop;
document.onmousemove = this.fnMove.bind(this);
document.onmouseup = this.fnUp.bind(this);
}.bind(this);
}
fnMove(event){
this.oDiv.style.left = event.clientX - this.disX + 'px';
this.oDiv.style.top = event.clientY - this.disY + 'px';
}
fnUp(){
document.onmousemove = null;
document.onmouseup = null;
}
}
//从父级继承
class LimitDrag extends Drag{
fnMove(event){
super.fnMove(event);//执行父级的fnMove函数
//以下内容为专属子级的操作
if(this.oDiv.offsetLeft <= 0){
this.oDiv.style.left = 0;
}
if(this.oDiv.offsetTop <= 0){
this.oDiv.style.top = 0;
}
}
}
new Drag('#div1')
new LimitDrag('#div2')
</script>
</body>
</html>