我有一个名为 Truncate 的函数,它正在截断文本。仅当带有类演示的左侧 div 的偏移高度超过右侧 div 的偏移高度时,我如何有条件地调用该函数。如果不满足条件,则返回原始内容。var textHolder = document.querySelector('.demo');var textHolder2 = document.querySelector('.demo2')var textHolderHeight = textHolder.offsetHeight + 'px'var textHolderHeight2 = textHolder2.offsetHeight + 'px'console.log(textHolderHeight)console.log(textHolderHeight2)var fullText = textHolder.innerHTML;var btn = document.querySelector('.btn');var textStatus = 'full'; // use this to check the status of text and toggle;function Truncate(textHolder, limit) { let txt = textHolder.innerHTML; if (txt.length > limit) { let newText = txt.substr(0, limit) + ' ...'; textHolder.innerHTML = newText; textStatus = 'truncated'; }}Truncate(textHolder, textHolder.offsetWidth / 10);function toggleText() { // here i want to show full text... // and also -> btn.innerHTML = 'Hide Text' | 'Show Text; if (textStatus === 'truncated') { textHolder.innerHTML = fullText; textStatus = 'full'; } else { Truncate(textHolder, textHolder.offsetWidth / 10); }}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>
1 回答
![?](http://img1.sycdn.imooc.com/5333a0aa000121d702000200-100-100.jpg)
SMILET
TA贡献1796条经验 获得超4个赞
您可以在每次需要调用时使用 if 语句Truncate。
if(textHolderHeight > textHolderHeight2){
Truncate(textHolder, textHolder.offsetWidth / 10);
}
或者将代码放在 Truncate 中,这样您就不必重复 if 语句。
function Truncate(textHolder, limit) {
let txt = textHolder.innerHTML;
if (txt.length > limit && textHolderHeight > textHolderHeight2) {
let newText = txt.substr(0, limit) + ' ...';
textHolder.innerHTML = newText;
textStatus = 'truncated';
}
}
添加回答
举报
0/150
提交
取消