多行文本实现展开更多

109 阅读1分钟

以上效果怎么实现呢?

CSS的 **shape-outside** 属性允许你定义一个非矩形的区域,文本将沿着这个区域流动。这可以用于创建一些更复杂的布局效果,如文字环绕图像。

shape-outside 属性的值可以是以下类型之一:

  • none:默认值,没有特定的形状,文本将正常流动。
  • <shape-box>:可以是 margin-boxborder-boxpadding-boxcontent-box,定义了一个矩形区域,文本将沿这个矩形区域流动。
  • <basic-shape>:定义了一个基本的形状,可以是 circle()ellipse()inset()polygon(),文本将沿这个形状流动。
  • <image>:定义了一个图像,文本将沿着图像的 alpha 通道(也就是透明部分)流动。

请注意,shape-outside 属性只对浮动元素有效。

html

<div id="box" class="content">
    <i class="icon"></i>
    <p id="text">
        ✨ You Have The Power To Change Your Story!  Trauma informed NLP Life Coach & Astrologer, trauma survivor. ✨ Thanks for reaching out, it's a pleasure to support you 🦋 Areas of expertise: Dating Advice, Dating Profile Optimization, Relationships, Communication, Break Ups, Attachment Theory, Trauma, Narcissistic Abuse, Masculine & Feminine Energy, Self Love, Body Image, Substance Abuse, Spiritual Awakening 🌹 💕 Please text me prior to booking to ensure I’m available. Thank you 🙏🏻
    </p>
</div>

css

.content {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 20px;
}
.content p {
    margin: 0;
    padding: 0;
    font-size: 16px;
    line-height: 20px;
}
.content .icon {
    display: none;
    width: 20px;
    height: 20px;
    shape-outside: content-box;
    -webkit-shape-outside: content-box;
    margin-top: 20px;
    background: url(./icon-arrow.png) center no-repeat;
}
.content.more .icon {
    display: block;
    float: right;
}

js

var textBox = document.getElementById('text')
var box = document.getElementById('box')
var height = textBox.scrollHeight
if (height > 40) {
    // 需要省略  box.classList.add('more')
} else { 
    box.classList.remove('more')
}