JavaScript简单拖拽事件(鼠标跟随事件)
本例演示简单来说分为两步:
第一步:鼠标按下时的事件对象操作。
第二步:鼠标移动时对事件对象的操作。
<style>
*{margin: 0;
padding: 0;
}
#box{width: 100px;height: 100px;background: #CCC;border: 1px solid #999;position: absolute;
top: 100px;left: 500px;text-align: center;line-height: 100px;cursor: move;
}
</style>
<div id="box">想要去哪?</div>
<script type="text/javascript">
var oBox =document.getElementById("box");
oBox.onmousedown = function(ev){
ev =ev ||event;
var oLeft = oBox.offsetLeft;
var oTop = oBox.offsetTop;
var a =ev.clientX-oLeft;
var b =ev.clientY-oTop;
oBox.onmousemove =function (ev){
ev = ev || event;
oBox.style.left =ev.clientX-a+'px';
oBox.style.top =ev.clientY-b+'px';
}
}
document.onmouseup =function(){
oBox.onmousemove =function(){
null;
}
}
</script>