30、JavaScript中简单拖拽DIV的实现

来源:互联网 发布:p2p运营模式数据图表 编辑:程序博客网 时间:2024/05/28 19:23
1、DIV拖拽的实现
     1.1 简易拖拽
             .拖拽原理
                --距离不变
                --三个事件
                   onmousedown  存储距离,并发生onmousemove
                   onmousemove  根据距离,计算div最新的位置
                   onmouseup    停止拖拽的发生,也就是当onmouseup时,onmousemove取消掉
                 --事件之间的关系
                   1. 鼠标的onmousedown没按下之前,鼠标的onmousemove移动事件不会发生

                       1.1 修改为,在onmousedown的时候,再添加onmousemove事件


2、代码

     2.1 css代码

               <style type="text/css">* {padding: 0px;margin: 0px;}#myDiv {width: 100px;height: 100px;background: red;position: absolute;}</style>

      2.2 JavaScript代码

             <script type="text/javascript">window.onload = function() {var oDiv = document.getElementById("myDiv");//保存鼠标位置disX,距离DIV左边边框的距离,就是,event.clientX - oDiv.offsetLeft;var disX = 0;//保存鼠标位置disY,距离DIV上边边框的距离,就是,event.clientY - oDiv.offsetTop;var disY = 0;/*1、当鼠标按下的时候,保存下当前DIV的top和left的数值*/oDiv.onmousedown = function(ev) {var oEvent = ev || event;disX = oEvent.clientX - oDiv.offsetLeft;disY = oEvent.clientY - oDiv.offsetTop;oDiv.style.cursor = "pointer";/*2、当鼠标移动的时候,计算DIV新的位置*/document.onmousemove = function(ev) {var oEvent = ev || event;var left = oEvent.clientX - disX;var top = oEvent.clientY - disY;/*可是区域的宽度大小*/var clientWidth = document.documentElement.clientWidth;var clientHeight = document.documentElement.clientHeight;/*4、进行边界的判断*//*检测左边的边界*/if (left < 0) {left = 0;}/*检测右边的边界*/else if (left > clientWidth - oDiv.offsetWidth) {left = clientWidth - oDiv.offsetWidth;}/*上边界的检测*/if (top < 0) {top = 0;}/*下边界的检测*/else if (top > clientHeight - oDiv.offsetHeight) {top = clientHeight - oDiv.offsetHeight;}oDiv.style.left = left + "px";oDiv.style.top = top + "px";}//3、当鼠标抬起来的时候,让onmousemove取消document.onmouseup = function() {//3.1 取消onmousemove事件oDiv.style.cursor = "default";document.onmousemove = null;document.onmouseup = null;}}};</script>

      2.3 html代码

        <body><div id="myDiv"></div></body>


0 0
原创粉丝点击