设置限制单词并在单词限制上调用新类

时间:2018-01-08 04:36:11

标签: javascript jquery html css limit

我在设置说明限制时遇到了问题。 当描述总词数超过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>

1 个答案:

答案 0 :(得分:1)

您需要将span显示为块并将其高度设置为显示的行数x行高度及其overflowhidden

现在转换&#34;了解更多&#34;到链接并将其移到span之外。添加一个单击事件监听器,将span设置回自动高度和内联显示。

修改仅显示&#34;了解详情&#34;当文字大于框时,您需要将可见高度clientHeight与总高(可见和不可见)高度scrollHeight进行比较。唯一的问题是,由于像素计算,它们之间总是存在微小的差异,因此您可以检查差异是否太小(比如说小于10)并隐藏&#34;阅读更多&#34;按钮。

&#13;
&#13;
(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();
})();
&#13;
.article-detail span {
  display: block;
  overflow: hidden;
  height: 2.2em; //Show 2 lines
  line-height: 1.1em;
}
&#13;
<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>
&#13;
&#13;
&#13;