更新时间:2023-12-05 22:02:46
您不需要javascript。一个简单的CSS text-overflow:省略号;
可以解决问题。
You don't need javascript for this. a simple css text-overflow: ellipsis;
can do the trick.
这是一种更好的/标准的截断长文本的方法,因为它将截断文本显示在确切位置,具体位置取决于字体大小,父容器的宽度,等等。。。用js不可能。这是一个演示:
It is a better/standard way to truncate the long text because it will truncate the text display at exact position which is depend on the font-size, width of parent container, etc... that is not possible simply with js. here is a demo:
var textHolder = document.querySelector('.demo');
var btn = document.querySelector('.btn');
function toggleText() {
textHolder.classList.toggle("truncate");
}
btn.addEventListener('click', toggleText);
toggleText(); //to truncate at first time
.truncate {
text-overflow: ellipsis;
/*BOTH of the following are required for text-overflow (overflow: hidden; and white-space: nowrap;)*/
overflow: hidden;
white-space: nowrap;
}
<section class="demo" id="demo">
Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>
<button class="readMore btn">Read More</button>
请注意,剪切 innerHTML
可能很危险,因为您可能在不适当的位置剪切并破坏了HTML代码的打开/关闭标签...
Note that cutting innerHTML
can be dangerous as you may cut at improper position and corrupt the HTML code opening/closing tags...