html中把多余文字轉化為省略號


在html中如果要把多余的文字顯示為省略號,那么有以下幾種方法:

單行文本:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
    .box{
        width: 200px;
        background-color: aqua;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }
    </style>
</head>
<body>
    <div class="box">講的是克辣椒的灑落看見斯科拉講的是拉開講的是了卡機快來撒建檔立卡時間到了撒快樂到家撒了看見撒快樂到家撒健康了</div>
</body>
</html>

多行文本:

1.利用-webkit-line-clamp屬性

.box{
    width: 200px;
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    border:solid 1px black;
}

 

缺點:僅適用於webkit內核或移動端頁面。在火狐,ie等瀏覽器並不支持。

2.用偽元素模擬實現

設定固定寬高,多余部分隱藏,在結尾用包含省略號(...)的元素覆蓋部分內容。

.box{
    height: 200px;
    width: 200px;
    position:relative;
    line-height:1.4em;
    height:4.2em;
    overflow:hidden;
}
.box::after {
    content:"...";
    font-weight:bold;
    position:absolute;
    bottom:0;
    right:0;
    padding:0 -20px 1px 45px;
    background-color:white;
}

這里用一個包含了省略號,且背景色為白色的偽元素遮蓋了部分內容。高度height 是行高 line-height 的三倍。需要顯示幾行文字就設置為幾倍。

這種思路實現較為簡單,兼容性也比較好。

注:如果要兼容ie6或7,則不能使用偽元素,可以使用一個<div>或者<span>標簽。如果要支持ie8,需要將::after寫成:after。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM