1. 程式人生 > >原生js實現 拖拽事件

原生js實現 拖拽事件

ons window mov .get end ret htm 坐標 document

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .box {
                width: 200px;
                height: 200px;
                background-color: #000000;
                position
: absolute; left: 0; top: 0; color: #FFFFFF; line-height: 200px; font-size: 20px; cursor: move; } </style> </head> <body> <div id="box" class="box"> 拖拽事件,文字選中
</div> <script type="text/javascript"> window.onload = function() { var oBox = document.getElementById("box"); //修正文字選中問題 oBox.onselectstart = function() { return false; } oBox.ondragstart
= function() { return false; } oBox.onmousedown = function(e) { var top = this.offsetTop; var left = this.offsetLeft; //起點 var originX = e.clientX; var originY = e.clientY; document.onmousemove = function(e) { var endX = e.clientX; var endY = e.clientY; //X軸、Y軸移動距離 var distanceX = endX - originX; var distanceY = endY - originY; oBox.style.left = (left + distanceX) + "px"; oBox.style.top = (top + distanceY) + "px"; } } //移除move事件 document.onmouseup = function() { document.onmousemove = null; } //鼠標移動mouseover oBox.onmousemove = function(e) { //box寬度高度 var width = this.offsetWidth; var height = this.offsetHeight; //box的top/left var top = this.offsetTop; var left = this.offsetLeft; //鼠標坐標 var mouseX = e.clientX; var mouseY = e.clientY; //最大坐標X,最大坐標Y var maxX = left + width; var maxY = top + height; if(maxX - mouseX < 10 && maxY - mouseY < 10) { this.style.cursor = "nw-resize"; } else { this.style.cursor = "move"; } } } </script> </body> </html>

原生js實現 拖拽事件