Heim  >  Fragen und Antworten  >  Hauptteil

javascript - web前端如何判断一段内容是否满两行?(屏幕宽度不同情况下)

有没有什么办法计算一段文字在不同大小屏幕下占用的行数?

如图,如果在用户手机屏幕宽度下内容超出两行则显示阅读全文,否则不显示阅读全文

大家讲道理大家讲道理2687 Tage vor1670

Antworte allen(6)Ich werde antworten

  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:10:51

    外层使用flex布局,设定高度行数, 或者外层给定最大高度max-height
    内层p放文字, 正常显示

    .outer {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        overflow: hidden;
    }
    .inner {
        display: block;
        oveflow: auto;
    }
    

    html结构:

    <p class="outer">
        <p class="inner">
            文本内容
        </p>
    </p>
    <p id="show-more"></p>
    

    然后判断两者高度:

    if ($('.inner').height() > $('.outer').height()) {
        $('#show-more').show();
    }
    

    这个时候显示“查看更多”

    Antwort
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:10:51

    思路是根据行高判断,一旦行高大于1行高度,说明内容出现了两行。以下是代码:

    html 如下:

        <p class="content">
          文本文本文本文本文本文本文本文本文本文本文本文本文本文本
          <a class="more" style="display:none">阅读全文</a>
        </p>

    js如下:

        const contentp = document.getElementsByClassName('content')[0];
        const style = window.getComputedStyle(contentp, null);
        const height = parseInt(style.height, 10);
        const lineHeight = parseInt(style.lineHeight, 10);
        if (height / lineHeight > 1) { //若行高大于1行,则显示阅读全文
          document.getElementsByClassName('more')[0].style.display = 'block';
        }

    码字不易,喜欢请点赞~

    Antwort
    0
  • 阿神

    阿神2017-05-16 13:10:51

    那就判断行高吧

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:10:51

    当前文本应该有一个单独的dom,获取其高度,行高 动态计算

    Antwort
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:10:51

    提供一种思路,你可以设置行高line-height为20px,然后等页面渲染完后,在js中用节点的offsetHeight属性,offsetHeight / 20就是行数

    Antwort
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 13:10:51

    elem.getClientRects()
    

    就好了

    Antwort
    0
  • StornierenAntwort