这个我很傻很天真, 我天真的认为,可以通过es6 写法,可以解决this问题,结果发现不行!
看如下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
#box {
position: absolute;
left:50px;
top:50px;;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<script>
// oop 真的很难写,我试试!原始的写法,this 指针问题,特别难折腾,还好有了es6,所以我用es6 写
// 真心搞不定 es6
class Drag{
constructor(id){
this.dx =0;
this.dy = 0;
// 得到目标对象
this.target = document.getElementById(id);
var that = this;
this.target.onmousedown = function(ev){
that.mdown(ev);
}
}
mdown(ev){
console.log(this);
var oEvent = ev|| window.event;
this.dx = oEvent.clientX - this.target.offsetLeft;
this.dy = oEvent.clientY-this.target.offsetTop;
console.log(this.dx,this.dy);
}
}
window.onload = function (){
new Drag('box');
}
</script>
</head>
<body>
<div id="box">
</div>
</body>
</html>
点击事件的this 指针,需要处理下!
初步的处理就很不错!
我接着写其它的逻辑
// oop 真的很难写,我试试!原始的写法,this 指针问题,特别难折腾,还好有了es6,所以我用es6 写
// 真心搞不定 es6
class Drag{
constructor(id){
this.dx =0;
this.dy = 0;
// 得到目标对象
this.target = document.getElementById(id);
var that = this;
this.target.onmousedown = function(ev){
that.mdown(ev);
return false;
}
document.onmouseup = function(ev){
that.mup(ev);
}
}
mup(ev){
document.onmousemove = null;
this.target.onmouseup = null;
}
mdown(ev){
console.log(this);
var oEvent = ev|| window.event;
this.dx = oEvent.clientX - this.target.offsetLeft;
this.dy = oEvent.clientY-this.target.offsetTop;
var that = this;
// console.log(this.dx,this.dy);
document.onmousemove = function(ev){
// 又出现this问题
that.mmove(ev);// 照样处理下!
}
}
mmove(ev){
var oEvent = ev|| window.event;
var x = oEvent.clientX - this.dx;
var y = oEvent.clientY- this.dy;
this.target.style.left = x + "px";
this.target.style.top = y + 'px';
}
}
看到没, this. 处理起来是相当的麻烦,这就是我学js面向对象的感受!