拖拽控制元素宽高

2021-06-09  本文已影响0人  web_afei

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
.test {
position: relative;
}

.line {
    position: absolute;
    width: 5px;
    top: 0;
    bottom: 0;
    right: 0;
    background: #ccc;
    cursor: col-resize;
}

</style>

<body>
<div class="test" style="width: 100px;height: 100px; border:1px solid red">
<div class="line"></div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
(function () { //绑定需要拖拽改变大小的元素对象 bindResize(('.test')[0],$('.line')[0]);
});

    function bindResize(el,line) {
        //初始化参数   
        var els = el.style,
            //鼠标的 X 和 Y 轴坐标   
            x = y = 0;
        //邪恶的食指   
        $(line).mousedown(function (e) {
            console.log(1);
            //按下元素后,计算当前鼠标与对象计算后的坐标  
            x = e.clientX - el.offsetWidth, y = e.clientY - el.offsetHeight;
            //在支持 setCapture 做些东东  
            el.setCapture ? (
                //捕捉焦点   
                el.setCapture(),
                //设置事件   
                line.onmousemove = function (ev) {
                    mouseMove(ev || event)
                },
                line.onmouseup = mouseUp
            ) : (
                //绑定事件   
                $(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp)
            )
            //防止默认事件发生   
            e.preventDefault()
        });
        //移动事件   
        function mouseMove(e) {
            //宇宙超级无敌运算中... 
            els.width = e.clientX - x + 'px' //改变宽度
            // els.height = e.clientY - y + 'px' //改变高度 
        }
        //停止事件   
        function mouseUp() {
            //在支持 releaseCapture 做些东东   
            el.releaseCapture ? (
                //释放焦点   
                el.releaseCapture(),
                //移除事件   
                el.onmousemove = el.onmouseup = null
            ) : (
                //卸载事件   
                $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp)
            )
        }
    }
</script>

</body>

</html>

上一篇下一篇

猜你喜欢

热点阅读