admin管理员组

文章数量:1122851

拖拽

<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="author" content="huyiwei"><meta name="generator" content="HBuilder X"><title>拖拽</title><style>#box{width: 100px;height: 100px;background-color: antiquewhite;position: absolute;}#box2{width: 100px;height: 100px;background-color: red;float: right;}</style></head><body><div id="box"></div><div id="box2"></div><script type="text/javascript">//拖拽的流程//1.当鼠标在被拖拽的元素上按下时,开始拖拽//onmousedown//2.当鼠标移动时被拖拽的元素跟随鼠标一起移动//onmousmove//3.当鼠标松开时,被拖拽的元素固定到当前位置//onmouseup//获取box对象var box = document.getElementById("box");//给box对象绑定一个鼠标按下的事件box.onmousedown = function(event){//求出div的偏移量//鼠标的x-元素的left值//鼠标的y-元素的top值var ol = event.clientX - box.offsetLeft;var ot = event.clientY - box.offsetTop;//跟随鼠标一起移动document.onmousemove = function(event){var x = event.pageX-ol;var y = event.pageY-ot;//修改box的位置box.style.left = x+"px";box.style.top = y+"px";	}//存在问题:给box绑定事件-->第一个div移动到第二个div时,鼠标松开即会失效box.onmouseup = function(){//固定box到松开位置//取消document的鼠标移动位置document.onmousemove = null;}//为了避免那种情况应该给document绑定document.onmouseup = function(){//取消document的鼠标移动位置document.onmousemove = null;//取消鼠标的松开事件document.onmouseup = null;}}</script></body>
</html>

本文标签: 拖拽