gpt4 book ai didi

javascript - 如何在 JavaScript 中切换 chop 文本?

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:18 25 4
gpt4 key购买 nike

这里的例子: enter image description here

如何将文本从“chop ”切换为“全文”?

就像我想在有人点击“阅读更多”按钮时切换全文,并在点击“隐藏文本”按钮时隐藏文本

片段:

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: ellipsis; 就可以做到这一点。

这是 chop 长文本的更好/标准方法,因为它会在确切位置 chop 文本显示,这取决于字体大小、父容器的宽度等……这仅用 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 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 代码的开始/结束标记...

关于javascript - 如何在 JavaScript 中切换 chop 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53386455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com