美文网首页
html +css 超出两行显示省略 及显示全文按钮

html +css 超出两行显示省略 及显示全文按钮

作者: Pino | 来源:发表于2021-10-11 17:05 被阅读0次

少废话 先看效果


省略号.gif

纯html +css+js 实现

原理 :判断内容是否超出父元素高度,即是否出现省略号,如果超出,则用定位将按钮 覆盖掉style设置的省略号
这里的全文按钮利用 (...+lable)作为一个整体 去个覆盖
全部拷贝在浏览器打开即可验证

<!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>
        * {
            font-size: 16px;
        }
        .content {
            width: 100%;
            position: relative;
            overflow: hidden;
            padding: 10px;
            box-sizing: border-box;
        }
        .text {
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-box-pack: center;
            -webkit-box-align: center;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }

        .show—all {
            display: none;
            position: absolute;
            bottom: 10px;
            right: 10px;
            background-color: #fff;
            line-height: 20px;
            z-index: 100;
        }

        .show—all label {
            color: red;
            border: 1px solid red;
            border-radius: 2px;
        }
    </style>
</head>

<body>
    <div class="content">
        <div class="text">
            发鬼地方个覆盖电饭锅电饭锅豆腐干豆腐电饭锅豆腐干豆腐豆腐干豆腐换地方大范甘迪发鬼地方个的发给对方
        </div>
        <span class="show—all">... <label onclick="showAll()">全文</label></span>
    </div>
</body>

</html>

<script>
    // 根绝内容宽度来显示 标签
    window.onresize = function () {
        var content = document.getElementsByClassName("content")[0]
        var textview = document.getElementsByClassName("text")[0]
        var showAll = document.getElementsByClassName("show—all")[0]

        var scrollHeight = textview.scrollHeight
        var height = content.clientHeight
        if (scrollHeight > height) {
            console.log('被省略了')
            showAll.style.display = 'block';
        }else{
            console.log('完全显示')
            showAll.style.display = 'none';
        }
    }
    function showAll() {
        alert("显示全文")
    }
</script>

另外一种效果,标签时刻跟随内>>> https://www.jianshu.com/p/94ad19b94667

相关文章

网友评论

      本文标题:html +css 超出两行显示省略 及显示全文按钮

      本文链接:https://www.haomeiwen.com/subject/hzxjoltx.html