Home  >  Q&A  >  body text

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

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

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

大家讲道理大家讲道理2687 days ago1668

reply all(6)I'll reply

  • 我想大声告诉你

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

    Use flex layout in the outer layer, set the number of rows of height, or give the maximum height max-height in the outer layer
    Place text in p in the inner layer, and display it normally

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

    html structure:

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

    Then judge the height of the two:

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

    At this time, "See more" will be displayed

    reply
    0
  • 给我你的怀抱

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

    The idea is to judge based on the row height. Once the row height is greater than 1 row height, it means that there are two rows of content. Here is the code:

    html is as follows:

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

    js is as follows:

        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';
        }

    It’s not easy to code, please like it if you like it~

    reply
    0
  • 阿神

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

    Then judge the row height

    reply
    0
  • 巴扎黑

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

    The current text should have a separate dom, get its height and line height and calculate it dynamically

    reply
    0
  • 曾经蜡笔没有小新

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

    To provide an idea, you can set the line-height to 20px, and then after the page is rendered, use the offsetHeight attribute of the node in js, offsetHeight / 20is the number of lines

    reply
    0
  • 过去多啦不再A梦

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

    Use

    elem.getClientRects()
    

    That’s it

    reply
    0
  • Cancelreply