Vue.js 中判断鼠标是否在画布矩形边框上的方法
<template>
<div>
<div ref="stage" @mousemove="checkMousePosition">
<div ref="rectangle" :style="rectangleStyle"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
mouseX: 0,
mouseY: 0,
rectangleX: 100,
rectangleY: 100,
rectangleWidth: 200,
rectangleHeight: 100,
};
},
computed: {
rectangleStyle() {
return {
position: 'absolute',
left: `${this.rectangleX}px`,
top: `${this.rectangleY}px`,
width: `${this.rectangleWidth}px`,
height: `${this.rectangleHeight}px`,
border: '1px solid black',
};
},
},
methods: {
checkMousePosition(event) {
this.mouseX = event.clientX;
this.mouseY = event.clientY;
if (
this.mouseX >= this.rectangleX &&
this.mouseX <= this.rectangleX + this.rectangleWidth &&
(this.mouseY === this.rectangleY || this.mouseY === this.rectangleY + this.rectangleHeight)
) {
console.log('鼠标在矩形的边框上');
}
},
},
};
</script>
<p>在上面的代码中,我们通过监听鼠标移动事件<code>@mousemove</code>并在<code>checkMousePosition</code>方法中获取鼠标的坐标<code>event.clientX</code>和<code>event.clientY</code>。然后,我们判断鼠标的坐标是否在矩形的边框上,如果是,则打印出'鼠标在矩形的边框上'。</p>
<p>注意,这里我们假设画布和矩形的位置都是相对于视口(viewport)的绝对位置。如果不是,你可能需要根据具体情况进行坐标的转换。</p>
原文地址: https://www.cveoy.top/t/topic/fviR 著作权归作者所有。请勿转载和采集!