按住鼠标的javascript瞬间

时间:2017-04-03 08:23:01

标签: javascript mouseevent

如何使用JavaScript从鼠标中获取坐标?我怎么才能只握住鼠标按住的坐标?

2 个答案:

答案 0 :(得分:1)

mousedown活动是你的朋友。只需点击并按住灰色区域:



var x = document.querySelector('#x')
var y = document.querySelector('#y')

document.querySelector('div').addEventListener('mousedown', function(e) {
  x.innerText = e.clientX
  y.innerText = e.clientY
}, false)

#target {
  width: 200px;
  height: 200px;
  background: gray;
  border: 1px solid black;
}

X: <span id="x"></span><br>
Y: <span id="y"></span>

<div id="target"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在用户可以单击的位置提供画布并捕获mouseDown事件,然后按照此示例和片段获取当前鼠标位置 https://www.w3schools.com/jsref/event_clientx.asp

var x = event.clientX;     // Get the horizontal coordinate
var y = event.clientY;     // Get the vertical coordinate
var coor = "X coords: " + x + ", Y coords: " + y;