JavaScript 原生JS实现 ‘拖拽‘ 效果

demo 1

按住鼠标进行移动的拖拽效果实现:

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
    width: 100px;
    height: 100px;
    background-color: pink;
    position: absolute;
    left: 0;
    top: 0;
    cursor: move;
}
</style>
</head>
<body>
    
<div class="box"></div>

<script>
var box = document.querySelector('.box')

box.onmousedown = function (ev){
    // 鼠标按下时在box中的偏移量
    var box_offsetX = ev.offsetX
    var box_offsetY = ev.offsetY
    // 在整个文档都可以拖拽box
    document.onmousemove = function (event){
        // 鼠标在页面中的坐标
        var x = event.pageX
        var y = event.pageY
        // 计算box的定位坐标
        var box_left = x - box_offsetX
        var box_top = y - box_offsetY

        // 限制box在视口范围内拖拽
        if (box_left <= 0) {
            box_left  = 0
        }
        if (box_left >= document.documentElement.clientWidth-box.clientWidth) {
            box_left = document.documentElement.clientWidth-box.clientWidth
        }

        if (box_top <= 0) {
            box_top  = 0
        }
        if (box_top >= document.documentElement.clientHeight-box.clientHeight) {
            box_top = document.documentElement.clientHeight-box.clientHeight
        }

        // 给box重新设置定位值
        box.style.left = box_left + 'px'
        box.style.top = box_top + 'px'
    }
    // 鼠标抬起时移除mousemove事件
    document.onmouseup = function (){
        document.onmousemove = null
    }
}

</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值