我是html的新手,我想在每个段落中设置所有字符只有30个字符。我的想法是截断它,但我遇到了如何截断所有段落的问题。
这是我的代码
<div class="" id="my-gallery-container">
<div class="item h200" data-order="31">
<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">
<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>
<div class="item h200" data-order="30">
<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">
<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>
<div class="item h200" data-order="29">
<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">
<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>
<div class="item h200" data-order="28">
<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">
<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>
这是我在该代码下的脚本
<script type="text/javascript">
function truncateText(selector, maxLength)
{
var element = document.querySelector(selector),
truncated = element.innerText;
if (truncated.length > maxLength)
{
truncated = truncated.substr(0,maxLength) + '...';
}
return truncated;
};
document.querySelector('p').innerText = truncateText('p', 30);
</script>
但它仅适用于第一段<p>
,如何截断所有<p>
?有人可以帮帮我吗?
谢谢
我希望我没有重新发布
答案 0 :(得分:1)
这是你正在寻找的吗?
function truncateText(selector, maxLength) {
// Get all the paragraphs on page
var paras = document.getElementsByTagName(selector);
// Loop over paragraphs
for (var i = 0; i < paras.length; i++) {
// Get the text of each paragraph element
var text = paras[i].innerText;
// Use javascripts substring to trim it and
// set it back as the text of the paragraph element
paras[i].innerText = text.substring(0,maxLength)
}
}
// Input the p tag
truncateText('p', 30)
https://jsfiddle.net/t68gue8g/2/
如果这是你想要的,按绿色勾号。
答案 1 :(得分:0)
如果您希望根据布局截断文本,可以使用CSS text-overflow
进行截断。
这将在截断的文本后添加省略号:
.parg {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: " Refugium meum et fortitudo mea, Deus meus, sperabo in eum "</p>
对于浏览器支持,您可以查看here。