指定范围内的拖拽效果

2021-08-31  本文已影响0人  升龙无涯

拖拽描述
小盒子在大盒子中拖拽,不允许小盒子超出大盒子的范围,一开始鼠标在小盒子的什么位置,拖拽过程中,鼠标一直就在小盒子的什么位置。
具体效果图如下:

拖拽效果
html结构代码:
<style>
.bigBox{
    width: 600px;
    height: 300px;
    background-color: hotpink;
    position: relative;
}
.smallBox{
    width: 100px;
    height: 100px;
    background-color: #00f;
    position: absolute;
    left: 0;
    top: 0;
}
</style>
<div class="bigBox">
    <div class="smallBox"></div>
</div>

js逻辑代码:

// 获取所有标签
var bigBox = document.querySelector('.bigBox');
var smallBox = document.querySelector('.smallBox');
// 给小盒子绑定鼠标按下事件
smallBox.addEventListener('mousedown', mousedown)
function mousedown() {
    // 获取事件对象
    var e = window.event;
    // 获取此时鼠标在小盒子上按下的位置
    var x = e.offsetX;
    var y = e.offsetY;
    // 给大盒子绑定移动事件
    bigBox.onmousemove = function(){
        // 获取事件对象
        var e = window.event;
        // 获取鼠标在浏览器中的位置
        var x1 = e.pageX;
        var y1 = e.pageY;
        // 根据鼠标位置计算小盒子的left和top = 鼠标位置 - 鼠标在小盒子的上位置 - 大盒子距离浏览器的距离
        var l = x1 - x - bigBox.offsetLeft;
        var t = y1 - y - bigBox.offsetTop;
        // 限制left和top的最小值
        if(l < 0) {
            l = 0;
        }
        if(t < 0) {
            t = 0
        }
        // 限制left和top的最大值
        if(l > bigBox.clientWidth - smallBox.offsetWidth) {
            l = bigBox.clientWidth - smallBox.offsetWidth
        }
        if(t > bigBox.clientHeight - smallBox.offsetHeight) {
            t = bigBox.clientHeight - smallBox.offsetHeight
        }
        // 将计算好的left和top设置给小盒子
        smallBox.style.left = l + 'px';
        smallBox.style.top = t + 'px';
    }
}
// 在整个文档范围内松开鼠标后,就不能移动小盒子了 - 解绑大盒子的移动事件
document.onmouseup = function(){
    bigBox.onmousemove = null
}
上一篇下一篇

猜你喜欢

热点阅读