我希望在鼠标指针悬停在红色 div 上并按下鼠标按钮时显示鼠标坐标。问题在于,当我在 div 外释放按钮并将鼠标指针返回到 div 上时,onmousemove 事件没有被移除。
注意:我不想使用任何像 jQuery 这样的库。
请注意主要情况:
我想用JavaScript做同样的事情。
注意:我不想使用任何像 jQuery 这样的库。
<script type="text/javascript">
window.onload = function(){
document.getElementById("thediv").onmousedown = AttachEvent;
}
function GetPos(e){
document.getElementById('X').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
document.getElementById('Y').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
function UnaatachEvent(e){
document.getElementById("thediv").onmousemove = null;
document.getElementById("thediv").onmouseup = null;
}
function AttachEvent(e){
document.getElementById("thediv").onmousemove = GetPos;
document.getElementById("thediv").onmouseup = UnaatachEvent;
}
</script>
</head>
<body>
<input type="text" id="X" size="3">X-position
<br/>
<br/>
<input type="text" id="Y" size="3">Y-position
<div style="width:100px;height:100px;background-color:red;margin:auto;" id="thediv">
</div>
</body>
更新:
使用jQuery非常容易:(仅在Firefox中测试过)
链接文本
$(document).ready(function(){
$('#thediv').mousedown(attachEvent);
});
function attachEvent(e){
$('#thediv').mousemove(getPos).mouseup(unattachEvent);
return false;
}
function getPos(e){
document.getElementById('X').value = e.pageX;
document.getElementById('Y').value = e.pageY;
return false;
}
function unattachEvent(e){
$('#thediv').unbind("mousemove", getPos).unbind("mouseup", unattachEvent);
请注意主要情况:
- 如果按钮在正方形外被点击,并且在按住按钮的同时移动到正方形内-不要更新位置。
- 如果按钮在正方形内被点击,并且在按住按钮的同时向外移动-停止更新,将其带回(不释放按钮),继续更新。
我想用JavaScript做同样的事情。
onmouseover
,如果左键仍然按下,则重新附加事件。 - Marcel Korpel