我正在尝试使用 SVG 在 Vue 中实现拖放功能,我可以点击一个形状,它会随着鼠标移动;但是,我不太清楚如何取消选择形状,以便将其放置在我发出双击事件的坐标上。这是我的 Vue 实例:
new Vue ({
el: '#meow',
data: {
x: '',
y: '',
rects: [
{x: 100, y: 100, width: 150, height: 150, fill: 'black'}
]
},
methods: {
moveHandler () {
this.$refs.rct[0].setAttribute('transform', `translate(${this.x-100}, ${this.y-100})`)
},
selectRect (e, idx) {
let temp = this.$refs.rct[idx]
this.$refs.wb.addEventListener('mousemove', this.moveHandler)
this.$refs.wb.addEventListener('dblclick', e => {
temp.removeAttribute('transform') // should I remove the transform attribute?
})
},
getMousePositionOnCanvas (e) {
var mousePos = this.getCoordinates(this.$refs.wb, e);
this.x = mousePos.x
this.y = mousePos.y
},
getCoordinates (canvas, evt) {
const rect = canvas.getBoundingClientRect()
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
}
}
})
有关工作演示:请参阅 https://codepen.io/p-adams/pen/gGwEQQ?editors=1010如您所见,如果我双击要放置形状的位置,形状仍会随鼠标移动。我在这里做错了什么?
最佳答案
所以你们非常亲密。您的对象被放置在双击上,但是当鼠标移动时该事件仍然存在,因此它会再次调用该函数来拖动它。您需要做的是删除该事件。
这是给你的代码片段和代码笔。
selectRect (e, idx) {
let temp = this.$refs.rct[idx]
this.$refs.wb.addEventListener('mousemove', this.moveHandler)
this.$refs.wb.addEventListener('dblclick', e => {
this.$refs.wb.removeEventListener('mousemove', this.moveHandler)
})
},
关于javascript - 如何在 Vue 中取消选择可拖动的 svg 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376527/