美文网首页
实现可拖拽插件

实现可拖拽插件

作者: 李永州的FE | 来源:发表于2017-08-08 15:19 被阅读0次
  • 一、js拖拽插件的原理
    常见的拖拽操作是什么样的呢?整过过程大概有下面几个步骤:

1、用鼠标点击被拖拽的元素

2、按住鼠标不放,移动鼠标

3、拖拽元素到一定位置,放开鼠标

这里的过程涉及到三个dom事件:onmousedown,onmousemove,onmouseup。所以拖拽的基本思路就是:

1、用鼠标点击被拖拽的元素触发onmousedown

(1)设置当前元素的可拖拽为true,表示可以拖拽

(2)记录当前鼠标的坐标x,y

(3)记录当前元素的坐标x,y

2、移动鼠标触发onmousemove

(1)判断元素是否可拖拽,如果是则进入步骤2,否则直接返回

(2)如果元素可拖拽,则设置元素的坐标

元素的x坐标 = 鼠标移动的横向距离+元素本来的x坐标 = 鼠标现在的x坐标 - 鼠标之前的x坐标 + 元素本来的x坐标

元素的y坐标 = 鼠标移动的横向距离+元素本来的y坐标 = 鼠标现在的y坐标 - 鼠标之前的y坐标 + 元素本来的y坐标

3、放开鼠标触发onmouseup

(1)将鼠标的可拖拽状态设置成false

  • 二、根据原理实现的最基本效果
    在实现基本的效果之前,有几点需要说明的:

1、元素想要被拖动,它的postion属性一定要是relative或absolute

2、通过event.clientX和event.clientY获取鼠标的坐标

3、onmousemove是绑定在document元素上而不是拖拽元素本身,这样能解决快速拖动造成的延迟或停止移动的问题

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style type="text/css">
      div{
          width: 50px;
          height: 50px;
          background-color: yellow;
          position: absolute;
          cursor: move;
      }

    </style>
</head>
<body>
<div></div>

<script>
    window.onload = function () {
        //获取需要拖拽的div
        var div1 = document.getElementsByTagName("div")[0];
        //添加鼠标按下事件
        div1.onmousedown = function (evt) {
            var oEvent = evt || event;
      
            //添加doc滑动时间
            document.onmousemove = function (evt) {
                var oEvent = evt || event;
                //重新计算div的left top值
                var left = oEvent.clientX
                var top = oEvent.clientY 
                //left  当小于等于零时,设置为零 防止div拖出document之外
                if (left <= 0) {
                    left = 0;
                }
                //当left 超过文档右边界  设置为右边界
                else if (left >= document.documentElement.clientWidth - div1.offsetWidth) {
                    left = document.documentElement.clientWidth - div1.offsetWidth;
                }
                if (top <= 0) {
                    top = 0;
                }
                else if (top >= document.documentElement.clientHeight - div1.offsetHeight) {
                    top = document.documentElement.clientHeight - div1.offsetHeight;
                }
                //重新给div赋值
                div1.style.top = top + "px";
                div1.style.left = left + "px";
            }
            //添加鼠标抬起事件
            div1.onmouseup = function () {
                //清空事件
                document.onmousemove = null;
                div1.onmouseup = null;
            }
        }
    }


</script>
</body>
</html>

相关文章

网友评论

      本文标题:实现可拖拽插件

      本文链接:https://www.haomeiwen.com/subject/nkjekxtx.html