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

2021-05-18  本文已影响0人  wxyzcctn

1. 内容描述

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

<div class="resizable">
    This paragraph is resizable, because the CSS resize property is set to 'both' on this
    element.
</div>
.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:

  <div class="CL">
    <div class="CLL">
      <div class="resizable"></div>
      <p class="CLL-content">
        改变左边的宽度
      </p>
    </div>
    <div class="CLR"></div>
  </div>
.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. 拖拽时从左侧改变宽度

  <div class="CR">
    <div class="CRL"></div>
    <div class="CRR">
      <div class="resizable"></div>
      <p class="CRR-content">
        改变右边的宽度
      </p>
    </div>
  </div>

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

参考:

上一篇 下一篇

猜你喜欢

热点阅读