首页 > 解决方案 > 在Javascript中有条件地调用函数?

问题描述

我有一个称为截断文本的函数。仅当带有演示类的左 div 的 offsetheight 超过右 div 的 offsetheight 时,我如何有条件地调用该函数。如果不满足条件,则返回原始内容。

这是一个演示

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>

<button class="readMore btn">Read More</button>
<br><br><br>

<section class="demo2" id="demo2">
  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!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!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>

提前谢谢你们。

标签: javascripthtmlcss

解决方案


您可以在每次需要调用时使用 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';
  }
}

推荐阅读