云計算-web第七次作業(yè)

項目要求

使用JS實現(xiàn)鼠標(biāo)拖拽效果

代碼演示

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box{
            position: absolute;
            width: 400px;
            height: 300px;
            background-color: #ff0000;
        }
    </style>
</head>
<body>
    <div id="box"></div>

    <script>
//獲取box標(biāo)簽
        let box = document.getElementById("box");
        //鼠標(biāo)左鍵按下進(jìn)行拖動
        box.onmousedown = function(e){
              //記錄鼠標(biāo)在div上的位置
              let offsetLeftX = e.clientX
              let offsetTopY = e.clientY
              //鼠標(biāo)在窗口中移動
              document.onmousemove = function(e2){
                //計算鼠標(biāo)在窗口中的位置
                      let clientX = e2.clientX
                      let clientY = e2.clientY
                      console.log(clientX,"clientX")
                      console.log(clientY,"clientY")
                      //計算div的位置
                      _left = clientX - offsetLeftX
                      _top = clientY - offsetTopY
                      console.log(_left,"left")
                      console.log(_top,"top")
                      //左邊界判斷
                      if(_left < 0){
                          _left = 0
                      }
                      //右邊界判斷
                      if(_left > document.documentElement.clientWidth - box.offsetWidth){
                          _left = document.documentElement.clientWidth - box.offsetWidth
                      }
                      //上邊界判斷
                      if(_top < 0){
                          _top = 0
                      }
                      //下邊界判斷
                      if(_top > document.documentElement.clientHeight - box.offsetHeight){
                          _top = document.documentElement.clientHeight - box.offsetHeight  
                      }

                       //定位div的位置
                     box.style.left = _left + "px"
                     box.style.top = _top + "px"
              }
        }

        //鼠標(biāo)抬起
        box.onmouseup = function(){
            //停止拖動
            document.onmousemove = null
        }
    </script>
</body>
</html>

效果演示

由于跟隨鼠標(biāo),圖片效果不明顯
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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