为了账号安全,请及时绑定邮箱和手机立即绑定

在Javascript中有条件地调用函数?

在Javascript中有条件地调用函数?

慕沐林林 2021-09-04 17:26:18
我有一个名为 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 回答

?
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';

  }

}


查看完整回答
反对 回复 2021-09-04
  • 1 回答
  • 0 关注
  • 187 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信