AWEI
AWEI

Reputation: 427

How to count the number of lines in an article using jQuery?

Excuse me, I currently have a requirement, such as the code I provided~

I need to use jquery to determine how many lines the original article contains. Although it is currently displayed on the screen with 2 lines, it is because I used CSS to make settings, but I need to know how many lines are in the original article~

Since I am a beginner in programming, I don’t know how to do it, I hope I can get your help, thank you

  .info{
      font-size: 15px;
      letter-spacing:1px;
      line-height: 1.5;
      margin-bottom: 8px;
      letter-spacing:0;
      overflow:hidden;
      text-overflow:clip;
      display:-webkit-box;
      -webkit-box-orient:vertical;  
      -webkit-line-clamp:2;
}
<div class="info">
  我是文章我是文章我是文章我是文章我是<br>
  文章我是文章我是文章我是文章
  我是文章我是文章我是文章我是文章我是<br>
  文章我是文章我是文章我是文章
  文章我是文章我是文章我是文章
 文章我是文章我是文章我是文章
</div>

Upvotes: 0

Views: 687

Answers (1)

Shakil
Shakil

Reputation: 715

You can get the height of a single character inside the container and then divide the total height of the container to get the line count. I made a simple example below, I'm not familiar with Chinese typography, so can't tell for sure if it's a full-proof solution.

$('#count').click(function() {
  var info = $('.info');
  var divTemp = $('#temp');
  divTemp.html(info.html());
  var divChar = document.createElement('div');
  divChar.innerText = '文';
  info.prepend(divChar);
  var lineCount = Math.round(divTemp.height() / divChar.clientHeight);
  $('#result').text(lineCount);
  $(divTemp).html('');
  $(divChar).remove();
})
.info {
  font-size: 15px;
  letter-spacing: 1px;
  line-height: 1.5;
  margin-bottom: 8px;
  letter-spacing: 0;
  overflow: hidden;
  text-overflow: clip;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
#temp {
  font-size: 15px;
  letter-spacing: 1px;
  line-height: 1.5;
  margin-bottom: 8px;
  letter-spacing: 0;
  text-overflow: clip;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  /* same as .info except the line clamp */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="info">
  我是文章我是文章我是文章我是文章我是<br>
  文章我是文章我是文章我是文章
  我是文章我是文章我是文章我是文章我是<br>
  文章我是文章我是文章我是文章
  文章我是文章我是文章我是文章
 文章我是文章我是文章我是文章
</div>
<div id="temp"></div> <!-- .info and #temp should be under the same parent -->

<span id="result"></span>
<button id="count">Count</button>

Upvotes: 1

Related Questions