我有一个 div,我给它指定了一些特定的 line-height
和 width
。
我把我的代码放在下面
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。
最佳答案
您可以为元素设置 overflow
和 max-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/