bir div'deki satır sayısını saymanın ve ilk çift satırın textContent'ini almanın bir yolu var mı?
Jan 08 2021
Amacım, bir div'deki ilk 3 satırın metnin uzunluğunu elde etmektir. Ör:
<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>
Div'de bulunan satırların sayısını şu şekilde sayabiliyorum:
function countLines() {
var el = document.getElementById('content');
var divHeight = el.offsetHeight
var lineHeight = parseInt(el.style.lineHeight);
var lines = divHeight / lineHeight;
alert("Lines: " + lines);
}
ancak yukarıdaki durumda ilk 3 satırın metninin uzunluğunu bulmanın bir yolu olup olmadığını bilmek istiyorum:
<p>hello how are you?</p>
<p>hello how are you too?</p>
<p>hello how are you john? </p>
diyelim ki yapıyorum:
var lines = countLines(); // 4
if (lines > 3) {
test = document.getElementById("content").textContent.length;
// get the length of first 3 lines
}
bu javascript'te mümkün mü?
Yanıtlar
2 WiatroBosy Jan 08 2021 at 15:42
JQuery'de istiyorsanız
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>
Js sonu
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>
Gene Simmons, KISS Çizgi Romanlarının Potansiyel Olarak "İnsanlığı Yeniden Yaratabileceğini" Söyledi
Donovan, Şarkılarından 1'ini The Beatles'ın "Lucy in the Sky with Diamonds" şarkısıyla karşılaştırdı
Kevin Jonas'ın Kızı Alena, Doğum Günü Fotoğrafında Büyümüş Görünüyor: '9 Yaşında Gerçek Hissetmiyor'
Tom Girardi Dolandırıcılık Suçlamalarından Yargılanma Yetkisinin Belirlenmesi İçin Duruşmaya Katıldı