如何将onmousemove与onmousedown连接? [英] How to connect onmousemove with onmousedown?
本文介绍了如何将onmousemove与onmousedown连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按下鼠标按钮并移动光标,以显示按下按钮时光标的坐标.当我停止单击时,它应该停止显示坐标.
I want to press the mouse button and move the cursor, showing the coordinates of the cursor while the button is pressed. When i stop clicking it should stop showing the coordinates.
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<style>
body {
height: 3000px;
}
</style>
</head>
<body>
<script>
(function() {
"use strict";
document.onmousedown = handleMouseDown;
function handleMouseDown(event) {
console.log("down")
}
document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
var dot, eventDoc, doc, body, pageX, pageY;
event = event || window.event;
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
console.log("left: " + event.pageX + "px -- right: " + event.pageY + "px");
}
})();
</script>
</body>
</html>
谢谢.
推荐答案
只需在mousedown
/mouseup
事件发生时附加/分离mousemove
处理函数:
Just attach/detach the mousemove
handling function upon mousedown
/mouseup
events:
document.onmousedown = function () {
document.onmousemove = handleMouseMove;
};
document.onmouseup = function () {
document.onmousemove = null;
};
function handleMouseMove(event) {
var dot, eventDoc, doc, body, pageX, pageY;
event = event || window.event;
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
console.log("left: " + event.pageX + "px -- right: " + event.pageY + "px");
}
这篇关于如何将onmousemove与onmousedown连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文