Gibt es eine Möglichkeit, die Anzahl der Zeilen in einem Div zu zählen und den Textinhalt der ersten paar Zeilen abzurufen? Javascript [Duplikat]

Jan 08 2021

Mein Ziel ist es, die Länge des Textinhalts der ersten 3 Zeilen in einem Div zu ermitteln. 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> 

Ich kann die Anzahl der im div enthaltenen Zeilen zählen, indem ich:

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

Ich möchte jedoch wissen, ob es eine Möglichkeit gibt, die Textlänge der ersten drei Zeilen zu ermitteln, im obigen Fall:

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

Nehmen wir an, ich mache:

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

ist das in javascript möglich?

Antworten

2 WiatroBosy Jan 08 2021 at 15:42

Wenn Sie in jQuery wollen

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>

Ende 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>