The*_*heV 3 javascript html5 css3
如何将文本从“截断”切换为“全文”?
就像我想在一个人单击“阅读更多”按钮时切换全文,并在单击“隐藏文本”按钮时也隐藏文本
片段:
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);Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
您不需要javascript。一个简单的CSS text-overflow: ellipsis;就能解决问题。
这是一种更好的/标准的截断长文本的方法,因为它将截断文本显示在确切的位置,具体位置取决于字体大小,父容器的宽度等...这在js中是无法实现的。这是一个演示:
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 timeRun Code Online (Sandbox Code Playgroud)
.truncate {
text-overflow: ellipsis;
/*BOTH of the following are required for text-overflow (overflow: hidden; and white-space: nowrap;)*/
overflow: hidden;
white-space: nowrap;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
请注意,切割innerHTML可能很危险,因为您可能会在不适当的位置切割并破坏HTML代码的打开/关闭标签...