HTML5實現div拖拽


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div style="border :1px solid red; width :500px;height :300px ; overflow:hidden; margin:20px">
    <div id="blackSquare" style="position: relative; width:50px; height:50px; background-color: black;cursor: pointer;color:#fff">wjw</div>
</div>
</body>
<script>
    window.onload = () => {
        //獲取拖拽實驗對象
        let el=document.getElementById("blackSquare");
        //在該對象上綁定鼠標點擊事件
        el.onmousedown = (e) => {
            //鼠標按下,計算鼠標觸點距離元素左側的距離
            let disX = e.clientX - el.offsetLeft;
			let disY = e.clientY - el.offsetTop;
            document.onmousemove = function (e) {
              //計算需要移動的距離
              let t = e.clientX - disX;
              let P = e.clientY - disY;
              //移動當前元素
              if (t >= 0 && t <= window.innerWidth - el.offsetWidth) {
                el.style.left = t + 'px';
              } 
			  //移動當前元素
              if (P >= 0 && P <= window.innerHeight - el.offsetHeight ) {
                el.style.top = P + 'px';
              } 
            };
            //鼠標松開時,注銷鼠標事件,停止元素拖拽。
            document.onmouseup = function (e) {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        }   
    }
</script>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM