CSS 实现拖拽改变布局大小

码农天地 -
CSS 实现拖拽改变布局大小

利用浏览器非overflow:auto元素设置resize可以拉伸的特性实现无JavaScript的分栏宽度控制。

推荐视频教程:《CSS视频教程-玉女心经版》

webkit浏览器下滚动条可以自定义,其中resize区域大小就是scrollbar的大小,于是,我们可以将整个拉伸区域变成和容器一样高。

实现原理

CSS中有一个resize属性,如果一个元素的overflow属性值不是visible,则通过设置resize属性可以拉伸这个元素尺寸。

但是,这种拉伸却有一个问题,那就是拖拽的区域太小了,就右下角那么一丢丢地方:

那有什么办法可以把这个拖拽区域变大呢?

后来经过我的研究发现,resize属性的拖拽bar和滚动条的拖拽bar是一个体系里面的东西,只需要对滚动条进行自定义,就能间接设置resize bar的尺寸。

例如:


.resize-bar::-webkit-scrollbar { width: 200px; height: 200px;}

此时,拉伸区域就很大了:

接下来做的事情就是把这个拖拽区域藏在某一栏布局的后面,然后透出部分宽度可以用来拖拽,如下图所示:

最后,我们的左右分栏采用自适应布局就能实现我们想要的效果。

代码如下:


.column { overflow: hidden;}.column-left { height: 400px; background-color: #fff; position: relative; float: left;}.column-right { height: 400px; padding: 16px; background-color: #eee; box-sizing: border-box; overflow: hidden;}.resize-save { position: absolute; top: 0; right: 5px; bottom: 0; left: 0; padding: 16px; overflow-x: hidden;}.resize-bar { width: 200px; height: inherit; resize: horizontal; cursor: ew-resize; opacity: 0; overflow: scroll;}/* 拖拽线 */.resize-line { position: absolute; right: 0; top: 0; bottom: 0; border-right: 2px solid #eee; border-left: 1px solid #bbb; pointer-events: none;}.resize-bar:hover ~ .resize-line,.resize-bar:active ~ .resize-line { border-left: 1px dashed skyblue;}.resize-bar::-webkit-scrollbar { width: 200px; height: inherit;}/* Firefox只有下面一小块区域可以拉伸 */@supports (-moz-user-select: none) { .resize-bar:hover ~ .resize-line, .resize-bar:active ~ .resize-line { border-left: 1px solid #bbb; } .resize-bar:hover ~ .resize-line::after, .resize-bar:active ~ .resize-line::after { content: ''; position: absolute; width: 16px; height: 16px; bottom: 0; right: -8px; background: url(./resize.svg); background-size: 100% 100%; }}


<p class="column"> <p class="column-left"> <p class="resize-bar"></p> <p class="resize-line"></p> <p class="resize-save"> 左侧的内容,左侧的内容,左侧的内容,左侧的内容 </p> </p> <p class="column-right"> 右侧的内容,右侧的内容,右侧的内容,右侧的内容 </p></p>

利用浏览器非overflow:auto元素设置resize可以拉伸的特性实现无JavaScript的分栏宽度控制。

webkit浏览器下滚动条可以自定义,其中resize区域大小就是scrollbar的大小,于是,我们可以将整个拉伸区域变成和容器一样高。

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

加个好友,技术交流

1628738909466805.jpg