Javascript 请解释一下这个代码的意思
我将在以下地址阅读教程: 我不理解我用星号标记的代码行Javascript 请解释一下这个代码的意思,javascript,dom,Javascript,Dom,我将在以下地址阅读教程: 我不理解我用星号标记的代码行 function Dragger(id) { this.isMouseDown = false; this.element = document.getElementById(id); var obj = this; this.element.onmousedown = function(event) { obj.mouseDown(event); } } Dragger.proto
function Dragger(id) {
this.isMouseDown = false;
this.element = document.getElementById(id);
var obj = this;
this.element.onmousedown = function(event) {
obj.mouseDown(event);
}
}
Dragger.prototype.mouseDown = function(event) {
var obj = this;
this.oldMoveHandler = document.body.onmousemove; /******/
document.body.onmousemove = function(event) { /******/
obj.mouseMove(event);
}
this.oldUpHandler = document.body.onmouseup; /******/
document.body.onmouseup = function(event) { /******/
obj.mouseUp(event);
}
this.oldX = event.clientX;
this.oldY = event.clientY;
this.isMouseDown = true;
}
Dragger.prototype.mouseMove = function(event) {
if (!this.isMouseDown) {
return;
}
this.element.style.left = (this.element.offsetLeft
+ (event.clientX - this.oldX)) + "px";
this.element.style.top = (this.element.offsetTop
+ (event.clientY - this.oldY)) + "px";
this.oldX = event.clientX;
this.oldY = event.clientY;
}
Dragger.prototype.mouseUp = function(event) {
this.isMouseDown = false;
document.body.onmousemove = this.oldMoveHandler; /******/
document.body.onmouseup = this.oldUpHandler; /******/
}
设置
document.body.onmousemove
是侦听document.body
元素上的mousemove
事件的一种(丑陋的)方法
因此,this.oldMoveHandler=document.body.onmousemove
只是存储对事件处理程序函数的引用(如果有的话)
请注意,附加事件处理程序时首选使用。如注释中所述,使用侵入式事件处理非常过时,现在不推荐使用 然而,为了回答您的问题,代码正在实现拖放,当按下鼠标触发mousedown事件时,mouseup和mouseover的当前事件处理程序(标记代码的前4行)被“保存”并替换为将执行拖放的事件处理程序
当拖动的元素被“删除”时,即触发mouseup事件,则mousemove和mouseup事件处理程序将替换为保存的原始事件处理程序(标记代码的最后两行)this.oldMoveHandler引用的目的是存储以前的页面开发人员添加到“document.body.onmousemove”中的任何事件处理程序,目的是不中断开发人员无疑要花费痛苦的时间构建的任何行为。事情是这样的:
我想澄清一下,你的“你强调过的行”是以“**”开头和结尾的行,对吗?我有点感觉ಠ_ಠ 2012年的一个教程建议使用老式的侵入式事件处理程序绑定。@Pointy我希望这是一个多年前的复制粘贴课程,这里有一个很好的例子,说明了这种模式:基本上,每个元素只能有一个
onmousemove
处理程序,所以如果您试图添加一个新的并且已经存在一个,保存并调用新处理程序中的现有处理程序。请注意,使用onmousemove
是完全没有必要的,因为您可以使用.addEventListener(“mousemove”,function(){…})
@Pointy CS 142:如何附加无限数量的事件ⁿᵒᵗ 开发web应用程序。