实现逻辑:
编写HTML页面,准备一个圆。
为圆添加onmousedown事件,在事件中获取鼠标按下时的位置,并计算鼠标该 位置与圆的距离。
为document添加onmousemove事件,当鼠标移动时对圆进行移动。
为document添加onmouseup事件,实现当鼠标松开后,不再移动圆。
代码提供:咸宁网站建设
<style>
div {width: 50px;height: 50px;background: #f00;border-radius: 50%; position: relative;}
</style>
<div></div>
<script>
var ele = document.getElementsByTagName('div')[0];
ele.onmousedown = function (e) {
var mx = e.pageX; //按下鼠标时鼠标当前位置
var my = e.pageY;
var elex = ele.offsetLeft;
var eley = ele.offsetTop;
var x = mx - elex;
var y = my - eley;
document.onmousemove = function (e) {
var curx = e.pageX;
var cury = e.pageY;
ele.style.left = curx - x + 'px';
ele.style.top = cury - y + 'px';
}
}
document.onmouseup=function(){
document.onmousemove=null
}
</script>