javascript - 如何使用 jquery 从 div 获取 3 行

标签 javascript html

我有一个 div,我给它指定了一些特定的 line-heightwidth

我把我的代码放在下面

document.getElementById("content").onload = countLines();
function countLines() {
   var el = document.getElementById('content');
   var divHeight = el.offsetHeight
   var lineHeight = parseInt(el.style.lineHeight);
   var lines = divHeight / lineHeight;
   console.log("Lines: " + lines);
}
<div id="content" style="width: 80px; line-height: 20px">
hello how are you? hello how are you? hello how are you? hello how are you?
</div>

但我只想显示 div 中的 3 行,并从 div 中删除所有其他生命,这 3 个数字是动态出现的,我想删除所有其他行使用 jquery。

最佳答案

您可以为元素设置 overflowmax-height css 属性,如下所示:

#content {
  overflow: hidden;
  max-height: 60px;
}

document.getElementById("content").onload = countLines();
function countLines() {
   var el = document.getElementById('content');
   var divHeight = el.offsetHeight
   var lineHeight = parseInt(el.style.lineHeight);
   var lines = divHeight / lineHeight;
   console.log("Lines: " + lines);
}
#content {
  overflow: hidden;
  max-height: 60px;
}
<div id="content" style="width: 80px; line-height: 20px;">
hello how are you? hello how are you? hello how are you? hello how are you?
</div>


更新:

document.getElementById("content").onload = countLines();

function countLines() {
    var el = document.getElementById('content');
    var divHeight = el.offsetHeight
    var lineHeight = parseInt(el.style.lineHeight);
    var lines = divHeight / lineHeight;
    console.log("Lines: " + lines);




    if (el.offsetHeight < el.scrollHeight || el.offsetWidth < el.scrollWidth) {

        var clone = $(el.cloneNode(true)).hide()
                        .addClass('clone').appendTo('body');

        var text = el.innerText;

        while (text.length > 0 && clone.height() > $(el).height()) {

            text = text.substr(0, text.length - 1);
            clone.text(text + "");

        }

        $(el).text(clone.text());

        console.log($(el).text());
    }

}
#content {
  overflow: hidden;
  max-height: 60px;
}

.clone {
  position: absolute;
  height: auto!important;
  max-height: inherit!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="content" style="width: 80px; line-height: 20px;">
hello how are you? hello how are you? hello how are you? hello how are you?
</div>

关于javascript - 如何使用 jquery 从 div 获取 3 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59464048/

相关文章:

javascript - 为什么我不能在 reduce 回调的元素上使用 string.charCodeAt()

javascript - 旧版浏览器中 classList `undefined` 的解决方法?

html - 另一个 div 与第一个 div 一起移动(在第一个 div 的动画上)

javascript - 在 Pangram 中设置字母类

jQuery隐藏元素,同时在页面布局中保留其空间

javascript - 如何动态修改 jQuery 多选下拉菜单的背景颜色?

javascript - 更改两个文本/字符串之间的所有内容

javascript - 如何在 jQuery 的 .hasClass() 中随机化 .class 名称

具有单选外观和感觉的 HTML <select> 多个

javascript - 如何仅在一定分辨率以上显示网站?