设置字数限制,并在字数限制上调用新类



我在设置描述限制时遇到问题。当描述总字数超过div的高度时,如何使(阅读更多(出现?并将描述设置为不超过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显示为块,并将其高度设置为显示的行数x行高及其overflowhidden

现在将"阅读更多"转换为链接并将其移出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>

最新更新