鼠標拖拽效果

作業(yè)分析

本次使用html與js樣式編寫效果如下


屏幕截圖 2025-03-26 200908.png

屏幕截圖 2025-03-26 200855.png

代碼實現(xiàn)

使用html代碼實現(xiàn)

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鼠標拖拽</title>
    <style>
        #box{
            width: 300px;
            height: 200px;
            background-color:olivedrab;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        //獲取標簽對象
        let box = document.getElementById("box")
        //1按下鼠標,獲取offsetx/offsety
        box.onmousedown = function(e){
            let ox =e.offsetX
            let oy =e.offsetY
            //2鼠標在網(wǎng)頁中移動(包含在1里面)
            document.onmousemove = function(e2){
                //獲取鼠標在窗口的位置
                let cx = e2.clientX
                let cy = e2.clientY
                //計算left 和 top
                let _left = cx - ox
                let _top = cy - oy
                if(_left<0){
                    _left=0
                }
                if(_top<0){
                    _top=0
                }
                if(_top>document.documentElement.clientHeight - box.offsetHeight){
                    _top=document.documentElement.clientHeight - box.offsetHeight
                }
              if(_left>document.documentElement.clientWidth - box.offsetWidth){
                _left = document.documentElement.clientWidth - box.offsetWidth
              }  
                //給div設置位置
                box.style.left = _left +"px"
                box.style.top = _top + "px"
            }
        }
        //3 和1事件對等,網(wǎng)頁中松開鼠標-停止移動
        document.onmouseup = function(){
            //停止移動
            document.onmousemove = null
        }
    </script>
</body>
</html>
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容