美文网首页
原生js实现拖拽

原生js实现拖拽

作者: 焦迈奇 | 来源:发表于2019-04-22 22:18 被阅读0次

onmousedown,onmousemove,onmouseup

先看js代码
.static定位:position的默认值,一般不设置position属性时,元素会按照正常的文档流进行排列。静态定位的元素不会受到top, bottom, left, right影响。

<script>
        var move=document.getElementsByClassName('move')[0];
        move.onmousedown=function (ev){
            var x=ev.clientX-this.offsetLeft;
            var y=ev.clientY-this.offsetTop;
            console.log(x,y);
            document.onmousemove=function (ev){
                var x1=ev.clientX;
                var y1=ev.clientY;
                if(x1<0){
                    x1=0;
                }else if(x1 >window.innerWidth-this.offsetWidth){
                    x1 = window.innerWidth-this.offsetWidth;
                }
                if(y1<0){
                    y1=0;
                }else if(y1 >window.innerHeight-this.offsetHeight){
                    y1 = window.innerHeight-this.offsetHeight;
                }
                move.style.left=x1-x+'px';
                move.style.top=y1-y+'px';
            };
            document.onmouseup=function (ev){
                document.onmousemove=null;
                document.onmouseup=null;
            };
        
    </script>

通过获取鼠标位置和目标的offset位置的差值,求出目标移动的初始位置,再通过onmousemove的鼠标位置的差值得出目标移动的x,y,赋值给目标的left,top,每次清除move和up,为了预防鼠标放上去的时候还会移动.

重中之重:移动的元素需要绝对定位,因为通过设置其left和top来实现移动的

只给添加position:relative,不添加top,left作用是:给子控件做定位使用。
他的子控件中有元素要设置positio:absolute的基准点;
子元素的absolute后的left,是相对于这个relative的左侧。如果没有设置其父元素没有设置relative;那就再往上找设置了relative的左侧;如果都没有那就是相对浏览器的左侧;

相关文章

网友评论

      本文标题:原生js实现拖拽

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