纯CSS检测文本是否溢出并显示展开收起按钮

239 阅读2分钟

重要点:

使用animation-timeline: scroll(self) 基于自身容器滚动判断该文字块是否可以滚动。

展开收起按钮中可以放一个checkbox按钮,判断是否被点击,当点击之后利用checked属性做其他容器样式的改变

@container 容器样式查询的使用

html

<div class="con">
  <div class="text-wrap">
    <div class="text-content">
      <label class="expand">
        <input type="checkbox" hidden/>
      </label>
      这里是文本展示区域,这里是文本展示区域
    </div>
  </div>
</div>

CSS

.text-wrap {
  display: flex;
  position: relative;
  padding: 8px;
  outline: 1px dashed #9747ff;
  border-radius: 4px;
  line-hight: 1.5;
  text-align: justify;
  font-family: cursive;
}
.expand {
  font-size: 80%;
  line-height: 20px;
  padding: 0 .5em;
  background-color: $9747ff;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
  float: right;
  clear: both;
  display: none;
}
.expand::after{
  content: '展开';
}
// scroll(self) self 表示监听自身的滚动,默认是最近的祖先滚动容器
.text-content{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  --trunk: false;
  animation: check 1s;
  animation-timeline: scroll(self);
}
.text-content::before {
 content: '';
 float: right;
 height: calc(100% - 22px);
}
.text-wrap:has(:checked) .text-content {
  -webkit-line-clamp: 999;
}
.text-wrap:has(:checked) .expand::after{
  content: '收起'
}

// 此行的作用是在点击展开之后按钮会跟着消失,因为css会检测出没有溢出,按钮就不会展示,所以在这里写在展开之后,始终显示按钮
.text-wrap:has(:checked) .expand {
  display: initial;
}

// 职业容器可滚动就会执行这个动画函数,我们将自定义样式设置为true
@keyframs check {
  from,to {
    --trunk: true
  }
}

// @container 样式查询, 当自定义样式为true时, 展示展开按钮
@container style(--trunk:true) {
  .expand {
    display: initial
  }
}

关键代码:

.expand{
  display: none; 
 } 
.text-content{ 
  --trunc: false; 
  animation: check 1s; 
  animation-timeline: scroll(self); 
 } 
@keyframes check{ 
  from,to { 
   --trunc: true; 
  } 
} 
@container style(--trunc: true) { 
  .expand{ 
    display: initial; 
  } 
}

文字超出一行省略号显示并鼠标移上的时候出现tooltip

<div class="wrap">
  <div class="txt" data-title="这是一段可以自动出现tooltip的文字">
   这是一段可以自动出现tooltip的文字
  </div>
</div>
.wrap {
  position: relative;
}
.txt {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  --trunc: false;
  animation: check 1s;
  animation-timeline: scroll(x self)
}
.txt::after {
  content: attr(data-title);
  position: absolute;
  top: 0;
  whidth: fit-content;
  left: 50%;
  margin: auto;
  transform: translate(-50%, -50%);
  background-color: rgba(0,0,0,.6);
  padding: 10px;
  border-radius: 4px;
  color: #fff;
  opacity: 0;
  visibility: hidden;
  transition: .2s .1s;
}

@keyframes check {
  from, to {
    --trunc: true;
  }
}

@container style(--trunc: true) {
  .txt:hover::after {
    opacity: 1;
    visibility: visible
  }
}