selleck -- 鼠标三大事件
1.
2.code:
<div id="drag" class="drag"></div> <script> window.onload = function (ev) { var drag = document.getElementById("drag"); var disX, disY;//鼠标点与控件左上角的距离 //鼠标按下,获取鼠标点与控件左上角的距离 drag.onmousedown = function (ev) { var event = ev || window.event; var pos = getPos(event); disX = pos.x - drag.offsetLeft; disY = pos.y - drag.offsetTop; } //鼠标移动,获取控件距离左边和上边的距离 drag.onmousemove = function (ev) { var event = ev || window.event; var pos = getPos(event); var drag_left = pos.x - disX; var drag_top = pos.y -disY; if (drag_left < 0) drag_left = 0; if (drag_top < 0) drag_top = 0; drag.style.left = drag_left + "px"; drag.style.top = drag_top + "px"; } //鼠标弹起 取消鼠标移动事件 drag.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } return false;//阻止FireFox按下的默认事件 } //获取鼠标在可视区的坐标,返回json格式 function getPos(ev) { var ev = ev || window.event; var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; return {x: ev.clientX + scrollLeft, y: ev.clientY + scrollTop } } </script>