云计算-web第七次作业

项目要求

使用JS实现鼠标拖拽效果

代码演示

<!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标签
        let box = document.getElementById("box");
        //鼠标左键按下进行拖动
        box.onmousedown = function(e){
              //记录鼠标在div上的位置
              let offsetLeftX = e.clientX
              let offsetTopY = e.clientY
              //鼠标在窗口中移动
              document.onmousemove = function(e2){
                //计算鼠标在窗口中的位置
                      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"
              }
        }

        //鼠标抬起
        box.onmouseup = function(){
            //停止拖动
            document.onmousemove = null
        }
    </script>
</body>
</html>

效果演示

由于跟随鼠标,图片效果不明显
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容