Javascript 在类中删除svg拖动的事件侦听器
我可以拖动,但不能移除拖动。我读到有一次我绑定了“这个” 它传递了一个新函数,我需要对局部变量做一些处理 但似乎做不到 代码:Javascript 在类中删除svg拖动的事件侦听器,javascript,svg,Javascript,Svg,我可以拖动,但不能移除拖动。我读到有一次我绑定了“这个” 它传递了一个新函数,我需要对局部变量做一些处理 但似乎做不到 代码: // import "./general"; class Home { constructor() { this.svgContainer = document.getElementById("svg-container"); console.log(this.svgContainer); this.pt = this.svgContain
// import "./general";
class Home {
constructor() {
this.svgContainer = document.getElementById("svg-container");
console.log(this.svgContainer);
this.pt = this.svgContainer.createSVGPoint();
this.circleSVG = document.getElementById("circleSVG");
}
startDrag() {
this.svgContainer.addEventListener("mousemove", this.mouseMoveFunc.bind(this));
this.circleSVG.addEventListener("mouseup", this.clearEvents.bind(this));
}
mouseMoveFunc(e) {
console.log(this.pt)
this.pt.x = e.clientX;
this.pt.y = e.clientY;
let svgPt = this.pt.matrixTransform(this.svgContainer.getScreenCTM().inverse());
this.circleSVG.setAttribute("cx", svgPt.x);
this.circleSVG.setAttribute("cy", svgPt.y);
}
clearEvents() {
console.log(this.svgContainer.attributes)
this.svgContainer.removeEventListener("mousemove", this.mouseMoveFunc);
this.circleSVG.removeEventListener("mouseup", this.clearEvents);
}
}
var home;
window.addEventListener("load", () => {
home = new Home();
});
以下是html:
<svg id="svg-container" width="500" height="500">
<circle cx="30" cy="30" r="30" id="circleSVG" onmousedown="home.startDrag()"></circle>
</svg>
如何使用类解决此问题?您的问题是您没有引用附加在
mousemove
要克服此问题,需要将构造函数中的movemove
事件与this
constructor() {
//.....
this.mouseMoveFunc = this.mouseMoveFunc.bind(this);
}
也可以使用mousedown
事件来删除mouseup
和mousemove
事件,而不是清除函数
班级主页{
构造函数(){
this.svgContainer=document.getElementById(“svg容器”);
console.log(this.svgContainer);
this.pt=this.svgContainer.createSVGPoint();
this.circleSVG=document.getElementById(“circleSVG”);
this.mouseMoveFunc=this.mouseMoveFunc.bind(this);
}
startDrag(){
this.svgContainer.addEventListener(“mousemove”,this.mouseMoveFunc);
this.circleSVG.removeEventListener('mouseup',this.startDrag);
//this.circleSVG.addEventListener(“mouseup”,this.clearEvents.bind(this));
}
阻力{
console.log(this.svgContainer);
this.svgContainer.removeEventListener(“mousemove”,this.mouseMoveFunc);
this.circleSVG.removeEventListener('mousedown',this.startDrag);
}
mouseMoveFunc(e){
console.log(this.pt)
这个.pt.x=e.clientX;
这个.pt.y=e.clientY;
设svgPt=this.pt.matrixTransform(this.svgContainer.getScreenCTM().inverse());
这个.circleSVG.setAttribute(“cx”,svgPt.x);
this.circleSVG.setAttribute(“cy”,svgPt.y);
}
}
var home;
window.addEventListener(“加载”,()=>{
家=新家();
});代码>