js鼠标能拖动调整div大小吗?back

发布于 2024-04-09  136 次阅读  共 1566 字


在JavaScript中实现鼠标拖动来调整div大小的功能,你需要用到HTML、CSS和JavaScript。以下是一种基本的实现方式:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Resizable DIV</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="resizable-div">
        <!-- 拖动条 -->
        <div id="resize-handle"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS (style.css)

#resizable-div {
    width: 200px;
    height: 200px;
    background-color: lightblue;
    position: relative;
    overflow: hidden;
}

#resize-handle {
    width: 10px;
    height: 10px;
    background-color: darkblue;
    position: absolute;
    bottom: 0;
    right: 0;
    cursor: nwse-resize; /* 可调整大小的光标 */
}

JavaScript (script.js)

document.addEventListener('DOMContentLoaded', function() {
    var resizeDiv = document.getElementById('resizable-div');
    var resizeHandle = document.getElementById('resize-handle');

    resizeHandle.addEventListener('mousedown', initDrag, false);

    var startX, startY, startWidth, startHeight;

    function initDrag(e) {
       startX = e.clientX;
       startY = e.clientY;
       startWidth = parseInt(document.defaultView.getComputedStyle(resizeDiv).width, 10);
       startHeight = parseInt(document.defaultView.getComputedStyle(resizeDiv).height, 10);
       document.documentElement.addEventListener('mousemove', doDrag, false);
       document.documentElement.addEventListener('mouseup', stopDrag, false);
    }

    function doDrag(e) {
       resizeDiv.style.width = (startWidth + e.clientX - startX) + 'px';
       resizeDiv.style.height = (startHeight + e.clientY - startY) + 'px';
    }

    function stopDrag() {
        document.documentElement.removeEventListener('mousemove', doDrag, false);    
        document.documentElement.removeEventListener('mouseup', stopDrag, false);
    }
});

这段代码将会创建一个可调整大小的div。当你拖动右下角的小方块时,div的大小会改变。这个简单的例子是入门级的,但你可以根据自己的需求调整和增强这个功能。