y a-t-il un moyen de compter le nombre de lignes dans un div et d'obtenir le texteContenu des deux premières lignes - Javascript [dupliquer]

Jan 08 2021

Mon objectif est d'obtenir la longueur de textContent des 3 premières lignes d'un div. Ex:

<div id="content" style="width: 100%;  
                line-height: 20px"> 
        <p>hello how are you?</p> 
        <p>hello how are you too?</p> 
        <p>hello how are you john? </p> 
        <p>hello how are you sphia?</p> 
    </div> 

Je suis capable de compter le nombre de lignes contenues dans le div en utilisant:

 function countLines() {
   var el = document.getElementById('content');
   var divHeight = el.offsetHeight
   var lineHeight = parseInt(el.style.lineHeight);
   var lines = divHeight / lineHeight;
   alert("Lines: " + lines);
}

cependant je veux savoir s'il existe un moyen de trouver la longueur du texte des 3 premières lignes, dans le cas ci-dessus:

 <p>hello how are you?</p> 
            <p>hello how are you too?</p> 
            <p>hello how are you john? </p> 

disons que je fais:

var lines = countLines(); // 4
if (lines > 3) {
  test = document.getElementById("content").textContent.length;
// get the length of first 3 lines
}

est-ce possible en javascript?

Réponses

2 WiatroBosy Jan 08 2021 at 15:42

Si vous voulez dans jQuery

let p = $('#content').find('p'); for (i = 0; i < 3; i++) { console.log($(p[i]).text().length);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" style="width: 100%;  
                line-height: 20px">
  <p>hello how are you?</p>
  <p>hello how are you too?</p>
  <p>hello how are you john? </p>
  <p>hello how are you sphia?</p>
</div>

Fin js

let p=document.getElementById("content");
let v=p.getElementsByTagName("p"); 
for (i = 0; i < 3; i++) {
  console.log(v[i].innerHTML.length);
}
<div id="content" style="width: 100%;  
                line-height: 20px">
  <p>hello how are you?</p>
  <p>hello how are you too?</p>
  <p>hello how are you john? </p>
  <p>hello how are you sphia?</p>
</div>