加载中...

AliveSevenの博客

Js实现元素拖拽

发表于: 2023-04-13 |

更新于: 2023-04-13 |

字数统计: 1831 |

阅读量: 0

前言:很多时候,我们业务中需要对鼠标点击的元素进行拖拽,使用原生JS实现这个方法,主要用到鼠标事件和监听。

  1. onmousedown:鼠标按下事件
  2. onmousemove:鼠标移动事件
  3. onmouseup:鼠标抬起事件

注意:

  1. 被拖拽的元素一定要是绝对定位,脱离文档流才可以移动
  2. 绑定拖拽的元素,移动和鼠标松开后是对document的绑定,因为移动的是整个div。

实现思路

  1. 先获取被拖拽元素所能移动的最大距离,超过这个距离就移动不了
  2. 给元素的onmousedown绑定一个function(e)事件
  3. 获取鼠标按下的原点距离盒子边缘的距离diffX和diffY
  4. 设置onmousemove事件,将被拖拽元素的left和top设置
  5. left的值是拖拽之后的那个位置的鼠标的x值减去diffX
  6. top的值是拖拽之后的那个位置的鼠标的y值减去diffY
  7. 设置鼠标松开事件onmouseup
html 复制代码
<body>
    <div class="box">
        <!-- 禁止图片拖拽打开新页面 -->
        <img src="https://tvax4.sinaimg.cn/large/ec43126fgy1gzp7qtgjs0j213a1jlnpd.jpg" alt="" ondragstart="return false">
    </div>
</body>
</html>

<style>
    /* 一定要绝对定位 */
    .box{
        width: 150px;
        position: absolute;
    }

    .box img{
        width: 100%;
        position: absolute;
    }
</style>

<script>
    // 获取盒子元素
    var box = document.querySelector('.box')
    // 获取元素最大能移动到的距离
    var maxLeft = window.innerWidth - box.offsetWidth;
    var maxTop = window.innerHeight - box.offsetHeight;
    // 鼠标按下盒子事件
    box.onmousedown = function(e){
        e = e || window.event
        // 获取鼠标按下的原点距离盒子边缘的距离
        let diffX = e.clientX - box.offsetLeft
        let diffY = e.clientY - box.offsetTop
        
        // 鼠标移动
        box.onmousemove = function(e){
            e = e || window.event
            // 移动之后记下鼠标在按下时的位置
            let x = e.clientX - diffX
            let y = e.clientY - diffY

            // 限定元素只能在浏览器可视窗口内移动
            x = x < 0 ? 0 : x > maxLeft ? maxLeft : x
            y = y < 0 ? 0 : y > maxTop ? maxTop : y

            box.style.left = x + 'px';
            box.style.top = y + 'px';
        }

        box.onmouseup = function(e){
            this.onmousemove = null 
            this.onmouseup = null
        }

    }
</script>

实现效果

AliveSeven
一个有趣的博客
文章
0
标签
0
分类
0
目录
©2021 - 2025 By AliveSeven
欢迎来到我的博客,谢谢你能在茫茫人海中发现我