您好,我写了一个白板,可以在其中进行绘图。我用svg绘制路径。它确实可以与我的EventHandlers一起工作,但是当我将鼠标移到上方时,我想删除这些处理程序。该应用程序的工作方式类似于,当您单击时,白板将获取所有事件处理程序,并且可以绘制一条线。当您不单击时,您不会绘画。现在,当我单击一次时,我会做出无休止的一行。
我希望这是可以理解的:/
谢谢
main() {
// hole whiteboard
let whiteboard = document.getElementById("whiteboard");
const color = "black";
let test2 = event => {
//console.log(event);
this.createSvgElement(whiteboard, color);
this.setup(event);
//alert("Ich bin reich!");
}
whiteboard.addEventListener("mousedown", test2);
},
createSvgElement(w, c){
this.whiteboard.removeEventListener("mousedown", this);
this.whiteboard = w;
this.segments = [];
this.points = [];
this.path = document.createElementNS("http://www.w3.org/2000/svg", "path");
this.path.setAttributeNS(null, "stroke", c);
this.path.setAttributeNS(null, "stroke-width", "2");
this.path.setAttributeNS(null, "fill", "transparent");
//console.log(this.path);
},
setup(event){
this.whiteboard.addEventListener("mousemove", e => {
const [x, y] = this.pos(e);
//console.log(x);
this.points.push({ x, y });
const test = this.path.getAttributeNS(null, "d");
//console.log(test);
this.path.setAttributeNS(null, "d", test + ` L${x},${y}`);
});
this.whiteboard.addEventListener("mouseleave", e =>{
this.whiteboard.removeEventListener("mousemove", this);
this.whiteboard.removeEventListener("mouseup", this);
this.whiteboard.removeEventListener("mouseleave", this);
});
this.whiteboard.addEventListener("mouseup", e =>{
this.whiteboard.removeEventListener("mousemove", this);
this.whiteboard.removeEventListener("mouseup", this);
this.whiteboard.removeEventListener("mouseleave", this);
});
},
pos(e){
const rect = this.whiteboard.getBoundingClientRect();
return [e.clientX - rect.left, e.clientY - rect.top];
},
答案 0 :(得分:1)
当您为特定元素处理mousedown
事件时,不能保证在同一元素上收到相应的mouseup
事件,因为在指针悬停在鼠标指针上方时可能会释放鼠标按钮不同的元素,甚至完全不在窗口之外。
唯一允许您执行此操作的API是setCapture,尽管这是非常不标准的。
处理此类鼠标事件的推荐方法是,将mousemove
和mouseup
事件附加到文档元素上,同时将鼠标放在目标元素上。之所以可行,是因为鼠标事件将冒泡,并且即使指针位于浏览器窗口之外,也会在文档上触发mouseup
。
简体:
const onMouseDown = e => {
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
}
const onMouseUp = e => {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
}
const onMouseMove = e => {
// Handle move event
}
this.whiteboard.addEventListener('mousedown', onMouseDown)
您呼叫removeEventListener
的方式也有错误:
this.whiteboard.removeEventListener("mousemove", this) ^^^^
第二个参数应该是要删除的事件侦听器函数; this
是组件对象实例。