实现功能:有水平3个DIV,左侧div和右侧div通过摁下鼠标左键修改div尺寸。
思路:设置一条drap-line线 并绑定方法,当摁下鼠标左键滑动时修改div尺寸,释放鼠标修改尺寸结束。
<!DOCTYPE html>
<html><head><meta charset="utf-8"><script src="jquery.js"></script><title></title></head><style>* {margin: 0;padding: 0;}body {display: flex;width: 100vw;height: 100vh;}.left,.right {width: 400px;background-color: aliceblue;height: 100%;}.center {flex: 3;background-color: antiquewhite;height: 100%;}.drap-line {width: 4px;height: 100%;background-color: brown;cursor: col-resize;}</style><body><div class="left"></div><div class="drap-line mr4"></div><div class="center"></div><div class="drap-line"></div><div class="right"></div><script>$(function(){resizeInit() ;});//左右两侧resize事件function resizeInit() {var isResizing = false;var DIV;var toward = 'left';$('body').on('mousedown','.drap-line',function (e) {isResizing = true;$(this).hasClass('mr4') ? (DIV = $('.left'), toward = 'left') : (DIV = $('.right'), toward = 'right');});$(document).on('mouseup',function (e) {isResizing = false;});$(document).on('mousemove',function (e) {if (!isResizing) return;var newWidth = 0;if (toward == 'left') {newWidth = e.pageX - DIV.offset().left;} else {newWidth = $(window).width() - e.pageX;}if (newWidth < 270) {newWidth = 270;} else if (newWidth > 900) {newWidth = 900;}DIV.width(newWidth);});};</script></body>
</html>