美文网首页
原生实现鼠标的拖拽功能

原生实现鼠标的拖拽功能

作者: 星球小霸王 | 来源:发表于2017-10-08 07:58 被阅读0次
    <body>
            <div class="box"></div>
            <script>
                var box = document.getElementsByTagName("div")[0];
                box.onmousedown = function(e){
                    var e = e || event;
    
                    var oldX = box.offsetLeft;
                    var oldY = box.offsetTop;
                    var oldmouseX = e.clientX;
                    var oldmouseY = e.clientY;
                    box.onmousemove = function(e){
                        var e = e || event;                                            
                        var curX = e.clientX;
                        var curY = e.clientY;
                        this.style.left = oldX+(curX-oldmouseX)+"px";
                        this.style.top = oldY+(curY-oldmouseY)+"px";
                    }
                    document.onmouseup = function(){
                        box.onmousemove = null;
                    }
                }
    
    
            </script>
        </body>
    

    相关文章

      网友评论

          本文标题:原生实现鼠标的拖拽功能

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