鼠标拖拽效果

<!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>
        let box = document.getElementById("box");
        box.onmousedown = function(e){
              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")
                      _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  
                      }
                     box.style.left = _left + "px"
                     box.style.top = _top + "px"
              }
        }
        box.onmouseup = function(){

            document.onmousemove = null
        }
    </script>
</body>
</html>
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 图片示例 代码演示
    z_e3bb阅读 36评论 0 0
  • 本次编写结果 代码展示:<!DOCTYPE html> Document #box {position: abs...
    风流_8cce阅读 1,046评论 0 0
  • 效果主要是实现网页中内容模块的鼠标拖拽,主要代码如下: <!DOCTYPE html> 鼠标拖动事件操作 #bo...
    L_2936阅读 694评论 0 0
  • 此为鼠标拖拽效果,多用于放大视图 用js展示出来示图: <!DOCTYPE html> Document ...
    画梅阅读 921评论 0 0
  • 鼠标拖拽效果分为3个事件 鼠标按下事件onmousedown, 事件源是点击的对象, 就是我们要拖拽的对象 鼠标移...
    LiYajie阅读 5,114评论 0 1