我在为描述设置限制时遇到了问题。 description总字数超过div高度时,如何让( Read More )出现?并将描述设置为不超过 div 高度?
.article-detail {
height: 160px;
}
<div class="article-detail">
<span>
The potential use cases for Blockchain spans across multiple industries and goes far beyond just Bitcoin. Financial services, Healthcare, Audit among many others; find your industry and we will transition you through Blockchain… ( Read more )
</span>
</div>
编辑 我试图让“阅读更多”在文本行超过 5 行时出现,并在文本行低于 5 时隐藏。有什么想法吗?
document.getElementById('read-more').addEventListener('click', function(event) {
event.preventDefault();
var text = document.querySelector('.bc-testing-detail');
text.style.height = 'auto';
text.style.display = 'inline';
this.style.display = 'none'; //Hide the 'read more' link
});
.article-detail {
height: 160px;
}
.bc-testing-detail {
display: block;
overflow: hidden;
height: 5.7em;
}
<div class="article-detail">
<span class="bc-testing-detail">
The potential use cases for Blockchain spans across multiple industries and goes far beyond just Bitcoin. Financial services, Healthcare, Audit among many others; find your industry and we will transition you through Blockchain
</span>
<a id="read-more" href="#"> ( Read More ) </a>
</div>
最佳答案
您需要将span
显示为 block 并将其高度设置为显示行数x 行高并将其overflow
设置为隐藏
.
现在将“阅读更多”转换为链接并将其移到span
之外。向其添加点击事件监听器,将 span
设置回自动高度和内联显示。
编辑 要仅在文本大于框时显示“阅读更多”链接,您需要将可见高度 clientHeight
与总高度(可见和不可见)高度 scrollHeight
。唯一的问题是,由于像素计算,它们之间始终存在微小差异,因此您可以检查差异是否太小(比如小于 10)并隐藏“阅读更多”按钮。
(function() {
var more = document.getElementById('read-more');
more.addEventListener('click', function(event) {
event.preventDefault();
var text = document.querySelector('.article-detail span');
text.style.height = 'auto';
text.style.display = 'inline';
this.style.display = 'none'; //Hide the 'read more' link
});
var text = document.querySelector('.article-detail span');
if (text.scrollHeight - text.clientHeight < 10)
more.click();
})();
.article-detail span {
display: block;
overflow: hidden;
height: 2.2em; //Show 2 lines
line-height: 1.1em;
}
<div class="article-detail">
<span>The potential use cases for Blockchain spans across multiple industries and goes far beyond just Bitcoin. Financial services, Healthcare, Audit among many others; find your industry and we will transition you through Blockchain. The potential use cases for Blockchain spans across multiple industries and goes far beyond just Bitcoin. Financial services, Healthcare, Audit among many others; find your industry and we will transition you through Blockchain</span>
<a id="read-more" href="#">( Read more )</a>
</div>
关于javascript - 设置字数限制并在字数限制上调用新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48144286/