使用CSS的resize属性实现左右拖拽改变布局大小

1. 内容描述

resize属性的具体用法可见MDN:https://developer.mozilla.org/zh-CN/docs/Web/CSS/resize
实现左右拖拽改变大小时:
HTML

This paragraph is resizable, because the CSS resize property is set to 'both' on this element.
.resizable {
  width: 200px;
  height: 200px;
  overflow: scroll;
  border: 1px solid black;
  resize: horizontal;
  cursor: ew-resize;
}

此时的div会出现滚动边框,此时可拖拽的区域只有右下角的一小块。


可拖拽区域

此时需要将这个区域扩大可进行如下设置。

.resizable::-webkit-scrollbar {
  width: 200px;
  height: inherit;
}
可拖拽区域改变大小后的结果

此时内部文字就被隐藏了,在实际使用时可以通过设置兄弟元素展示文字。

2. 拖拽时从右侧改变宽度

HTML:

  

改变左边的宽度

.CL{
  height: 200px;
  width: 600px;
  border: 1px solid;
  display: flex;
}
.CLR{
  height: 200px;
  width: 200px;
  border: 1px solid red;
  flex:1
}
.CLL {
  position: relative;
}
.CLL-content {
  margin:0;
  height: 200px;
  position: absolute;
  top: 0;
  right: 5px;
  bottom: 0;
  left: 0;
  border: 1px solid;
}
.resizable {
  resize: horizontal;
  cursor: ew-resize;
// 鼠标箭头改为左右方向箭头
  width: 200px;
  height: 200px;
  overflow: scroll;
  border: 1px solid black;
  opacity:0;
}
.resizable::-webkit-scrollbar {
  width: 200px;
  height: inherit;
}
/* 拖拽线 */
.resize-line {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  border-right: 2px solid #eee;
  border-left: 1px solid #bbb;
  pointer-events: none;
}
.resizable:hover ~ .resize-line,
.resizable:active ~ .resize-line {
  border-left: 1px dashed skyblue;
}
image.png

3. 拖拽时从左侧改变宽度

  • 从左侧进行拖拽时通过旋转父元素和内容元素实现
    HTML
  

改变右边的宽度

CSS

.CR{
  height: 200px;
  width: 600px;
  border: 1px solid;
  display: flex;
}
.CRL{
  height: 200px;
  width: 200px;
  border: 1px solid red;
  flex:1
}
.CRR {
  position: relative;
  transform:rotateY(180deg);
}
.CRR-content {
  transform:rotateY(180deg);
  margin:0;
  height: 200px;
  position: absolute;
  top: 0;
  right: 5px;
  bottom: 0;
  left: 0;
  border: 1px solid;
}
.resizable {
  resize: horizontal;
  cursor: ew-resize;
// 鼠标箭头改为左右方向箭头
  width: 200px;
  height: 200px;
  overflow: scroll;
  border: 1px solid black;
  opacity:0;
}
.resizable::-webkit-scrollbar {
  width: 200px;
  height: inherit;
}
/* 拖拽线 */
.resize-line {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  border-right: 2px solid #eee;
  border-left: 1px solid #bbb;
  pointer-events: none;
}
.resizable:hover ~ .resize-line,
.resizable:active ~ .resize-line {
  border-left: 1px dashed skyblue;
}
image.png

效果链接:http://js.jirengu.com/voleracixe/2/edit

参考:

  • 张鑫旭纯《CSS实现分栏宽度拉伸调整》:https://www.zhangxinxu.com/study/201903/css-idea/behavior-stretch.php?aside=0
  • MDN-resize:https://developer.mozilla.org/zh-CN/docs/Web/CSS/resize

你可能感兴趣的:(使用CSS的resize属性实现左右拖拽改变布局大小)