如何在JavaScript中切换截断文本? [英] How to toggle Truncate text in JavaScript?
问题描述
此处为示例:
Example here:
如何将文本从截断切换为全文 ?
How to toggle text from 'truncate' to 'full text'?
就像我想在用户单击阅读更多按钮时切换全文,并且在单击隐藏文本按钮时也隐藏文本
like i want to toggle full text when a person clicks on 'read more' button and also hide text when 'hide text' button is clicked
代码段:
var textHolder = document.querySelector('.demo');
var btn = document.querySelector('.btn');
function Truancate(textHolder, limit) {
let txt = textHolder.innerHTML;
if (txt.length > limit) {
let newText = txt.substr(0, limit) + ' ...';
textHolder.innerHTML = newText;
}
}
Truancate(textHolder, textHolder.offsetWidth / 10);
function toggleText() {
// here i want to show full text...
// and also -> btn.innerHTML = 'Hide Text' | 'Show Text;
}
btn.addEventListener('click', toggleText);
<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>
推荐答案
您不需要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...
这篇关于如何在JavaScript中切换截断文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!