方法可分為兩種 第一種 使用iviewUI 的split 面板分割組件 第二種就是自己寫一個監聽鼠標點擊移動位置
一. 使用iview 的split 面板分割組件
這里是說明鏈接 https://www.cnblogs.com/wjian0916/p/16227825.html
二. 監聽鼠標
1.展示效果
2.頁面代碼
1 <div class="box" ref="box"> 2 <index-left class='left' ref="indexLeft" @refreshIndex="leftChange"></index-left> 3 <div class="resize" title="收縮側邊欄"></div> 4 <index-right class='right' ref="indexRight" @refreshIndex="rightChange"></index-right> 5 </div>
3.js 代碼
mounted () { this.dragControllerDiv(); },
1 dragControllerDiv: function () { 2 var resize = document.getElementsByClassName('resize') 3 var left = document.getElementsByClassName('left') 4 var right = document.getElementsByClassName('right') 5 var box = document.getElementsByClassName('box') 6 for (let i = 0; i < resize.length; i++) { 7 // 鼠標按下事件 8 resize[i].onmousedown = function (e) { 9 var startX = e.clientX // 基於瀏覽器位置這里與邊框還有40的距離 10 // 鼠標拖動事件 11 document.onmousemove = function (e) { 12 resize[i].left = startX - 40 13 var endX = e.clientX 14 var moveLen = resize[i].left + (endX - startX) // (endx-startx)=移動的距離。resize[i].left+移動的距離=左邊區域最后的寬度 15 var maxT = box[i].clientWidth - resize[i].offsetWidth // 容器寬度 - 左邊區域的寬度 = 右邊區域的寬度 16 if (moveLen < 32) moveLen = 32 // 左邊區域的最小寬度為32px 17 if (moveLen > maxT - 150) moveLen = maxT - 150 // 右邊區域最小寬度為150px 18 resize[i].style.left = moveLen // 設置左側區域的寬度 19 for (let j = 0; j < left.length; j++) { 20 // left[j].style.width = (moveLen / box[i].clientWidth) * 100 + '%' 21 left[j].style.width = moveLen + 'px' 22 right[j].style.left = left[j].style.width 23 resize[i].style.left = left[j].style.width 24 // right[j].style.width = ((box[i].clientWidth - moveLen) / box[i].clientWidth) * 100 + '%' 25 right[j].style.width = (box[i].clientWidth - moveLen) + 'px' 26 } 27 } 28 // 鼠標松開事件 29 document.onmouseup = function (evt) { 30 document.onmousemove = null 31 document.onmouseup = null 32 resize[i].releaseCapture && resize[i].releaseCapture() // 當你不在需要繼續獲得鼠標消息就要應該調用ReleaseCapture()釋放掉 33 } 34 resize[i].setCapture && resize[i].setCapture() // 該函數在屬於當前線程的指定窗口里設置鼠標捕獲 35 return false 36 } 37 } 38 }
4. 樣式代碼
1 .left { 2 position: absolute; 3 left: 0; 4 width: calc(15%); 5 height: 100%; 6 overflow-y: auto; 7 overflow-x: auto; 8 float: left; 9 } 10 .resize { 11 position: absolute; 12 left: 15%; 13 top: 0; 14 bottom: 0; 15 width: 5px; 16 cursor: col-resize; 17 z-index: 100; 18 background-color: transparent; 19 border-left: 1px solid #ececec; 20 } 21 .right { 22 position: absolute; 23 left: 15%; 24 width: 85%; 25 height: 100%; 26 float: left; 27 } 28 .box { 29 width: 100%; 30 height: 663px; 31 }