在前端中,多行超出省略最好的解决办法

Lynn
  • 175

css多行省略也就只有chrome中可以实现,在其他浏览器貌似不行,js去解决的话,又出现一闪的效果。这种体验又不好,哪位大神有更好的解决办法?

回复
阅读 3.3k
3 个回答

比较靠谱简单的做法就是设置相对定位的容器高度,用包含省略号(…)的元素模拟实现;

p {
    position:relative;
    line-height:1.4em;
    /*三倍line-height去显示三行*/
    height:4.2em;
    /*多余的隐藏*/
    overflow:hidden;
}
p::after {
    content:"...";
    font-weight:bold;
    position:absolute;
    bottom:0;
    right:0;
    padding:0 20px 1px 45px;
    background:url(http://css88.b0.upaiyun.com/css88/2014/09/ellipsis_bg.png) repeat-y;
}

text-overflow: ellipsis;
刚去caniuse上看了下,除了firefox最早期的几个版本不支持之外,其他的都支持的

如果需要跨内核支持,允许固定高的可以借助多层嵌套浮动这么做:

<!doctype html><html><body>
<style>
.ellipsis {
    overflow: hidden;
    position: relative;
}
.ellipsis-more-top {/*push down .ellipsis-more*/
    content: "";
    float: left;
    width: 5px;
}
.ellipsis-text-container {
    float: right;
    width: 100%;
    margin-left: -5px;
}
.ellipsis-more-container {
    float: right;
    position: relative;
    left: 100%;
    width: 5px;
    margin-left: -5px;
    border-right: solid 5px transparent;
    white-space: nowrap;
}
.ellipsis-placeholder {/*keep text around ,keep it transparent ,keep same width and height as .ellipsis-more*/
    float: right;
    clear: right;
    color: transparent;
}
.ellipsis-placeholder-top {/*push down .ellipsis-placeholder*/
    float: right;
    width: 0;
}
.ellipsis-more {/*ellipsis things here*/
    float: right;
}
.ellipsis-height {/*the total height*/
    height: 3.6em;
}
</style>
<div class="ellipsis ellipsis-height ellipsis-line-height">
    <div class="ellipsis-more-top ellipsis-height"></div>
    <div class="ellipsis-text-container">
        <div class="ellipsis-placeholder-top ellipsis-height ellipsis-margin-top"></div>
        <div class="ellipsis-placeholder">
           <span>...</span><span>more</span>
        </div>
        <span class="ellipsis-text">text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </span>
    </div>
    <div class="ellipsis-more-container ellipsis-margin-top">
        <div class="ellipsis-more">
            <span>...</span><span>more</span>
        </div>
    </div>
</div>
</body></html>

如需不定高,可借助line-clampfloat可以在webkit上实现自适应高的定制的多行省略,详细解释看黑科技:CSS定制多行省略

宣传栏