--- title: mousemove slug: Web/API/Element/mousemove_event tags: - API - DOM - Event - Interface - NeedsBrowserCompatibility - NeedsMobileBrowserCompatibility - NeedsSpecTable - Reference translation_of: Web/API/Element/mousemove_event ---
{{APIRef}}

当指针设备( 通常指鼠标 )在元素上移动时, mousemove 事件被触发。

基本信息

是否冒泡 Yes
是否可取消 Yes
接口 {{domxref("MouseEvent")}}
事件处理 {{domxref("GlobalEventHandlers.onmousemove", "onmousemove")}}

例子

下面的例子将使用 {{domxref("Element/mousedown_event", "mousedown")}}, mousemove 以及 {{domxref("Element/mouseup_event", "mouseup")}} 事件,实现一个允许用户在 HTML5 canvas绘图的功能。这个例子的功能很简单:线的粗细设置为1,颜色始终为黑色。

当页面加载完成,我们使用变量 myPics 和context分别保存ID为myPics的DOM元素和接下来需要加工的的2d元素。

mousedown事件被触发时,绘图也开始了。首先,我们将鼠标的x坐标和y坐标分别赋值给变量xy,然后设置isDrawingtrue

当鼠标在页面上移动时,mousemove事件被触发。当isDrawing为true时,事件处理程序将会调用drawLine函数,该函数从变量xy所指的位置开始,到现在鼠标所在的位置,画一条线。

drawLine()调用结束时,我们需要把坐标赋值到xy中。

mouseup事件绘制图形的最后一段,并把xy设置为0.通过设置isDra

mouseup事件绘制图形的最后一段,并把xy设置为0.通过设置isDrawing为false,可以停止绘制。

HTML

<h1>Drawing with mouse events</h1>
<canvas id="myPics" width="560" height="360"></canvas>

CSS

canvas {
  border: 1px solid black;
  width: 560px;
  height: 360px;
}

JavaScript

// When true, moving the mouse draws on the canvas
let isDrawing = false;
let x = 0;
let y = 0;

const myPics = document.getElementById('myPics');
const context = myPics.getContext('2d');

// The x and y offset of the canvas from the edge of the page
const rect = myPics.getBoundingClientRect();

// Add the event listeners for mousedown, mousemove, and mouseup
myPics.addEventListener('mousedown', e => {
  x = e.clientX - rect.left;
  y = e.clientY - rect.top;
  isDrawing = true;
});

myPics.addEventListener('mousemove', e => {
  if (isDrawing === true) {
    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
    x = e.clientX - rect.left;
    y = e.clientY - rect.top;
  }
});

window.addEventListener('mouseup', e => {
  if (isDrawing === true) {
    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
    x = 0;
    y = 0;
    isDrawing = false;
  }
});

function drawLine(context, x1, y1, x2, y2) {
  context.beginPath();
  context.strokeStyle = 'black';
  context.lineWidth = 1;
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
  context.stroke();
  context.closePath();
}

结果

{{EmbedLiveSample("Examples", 640, 450)}}

参考

gui Status
{{SpecName('UI Events', '#event-type-mousemove', 'mousemove')}} {{Spec2('UI Events')}}
{{SpecName('DOM3 Events', '#event-type-mousemove', 'mousemove')}} {{Spec2('DOM3 Events')}}

浏览器兼容性

{{Compat("api.Element.mousemove_event")}}

See also