JS实现拖动效果

有个问题就是该模块要使用定位,因为有left,top属性使用,绝对定位和相对定位都行,当然你也可使用margin-left,和margin-top这2个属性,替换left,top也是可以得

这样就不用定位,仅供参考

#move{ 300px;height: 300px;border: 1px solid red;position: absolute;top: 0px;left: 0px;background: #ccc;}
    move();
    function move(){
        var $move = document.getElementById('move');
        var params = {
            flg:false,//是否点击
            left:0,//模块初始位置
            top:0,
            currentX:0,//模块在屏幕中的位置
            currentY:0
        }
        //初始化的时候获取模块的位置
          params.left = getCss($move,'left');
        params.top = getCss($move,'top');
        $move.onmousedown=function(e){
            //获取鼠标在屏幕中点下的位置
            params.flg = true;
            var e = e || window.event;
            params.currentX = e.clientX;
            params.currentY = e.clientY;
        }
        //移动
         $move.onmousemove=function(e){
            if(params.flg) {
                var e = e || window.event;
                //当前在屏幕中的位置,减去开始在屏幕中的位置就等于移动的距离
                var disX  = e.clientX - params.currentX;
                var disY  = e.clientY - params.currentY;
                //初始位置加上移动距离,就是当前位置
                $move.style.left = parseInt(params.left)+ disX + "px";
                $move.style.top = parseInt(params.top)+ disY + "px";
            }
        }
         //移动结束
        $move.onmouseup=function(){
            //鼠标离开重新获取位置
            params.flg = false;
            params.left = getCss($move,'left');
            params.top = getCss($move,'top');
        }
        //获取最终样式
        function getCss(ele,key){
            return ele.currentStyle ? ele.currentStyle[key]
                    :document.defaultView.getComputedStyle(ele,null)[key];
        };
    }
原文地址:https://www.cnblogs.com/bruce-gou/p/5607147.html