1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>拖动侧边栏</title> <style> * { user-select: none; } .wrap { height: 500px; display: flex; } .left { position: relative; height: 100%; background-color: #ccc; width: 200px; } .line { position: absolute; top: 0; right: 0; width: 4px; height: 100%; background-color: #000; cursor: col-resize; } .right { flex: 1; height: 100%; background-color: #f99; } </style> </head> <body> <div class="wrap"> <div id="left" class="left"> <div id="line" class="line"></div> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> </div> <div id="right" class="right">2</div> </div> <script>
function dragSidebar() { const minWidth = 200; const maxWidth = 500; const left = document.querySelector("#left"); const line = document.querySelector("#line"); const right = document.querySelector("#right");
line.onmousedown = function (e) { const startX = e.clientX; line.left = line.offsetLeft; document.onmousemove = function (e) { const moveLen = line.left + (e.clientX - startX); if (moveLen >= minWidth && moveLen <= maxWidth) { line.style.left = moveLen + "px"; left.style.width = moveLen + "px"; right.style.width = document.body.clientWidth - moveLen + "px"; } }; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; }; }; } dragSidebar(); </script> </body> </html>
|