函数执行后,Javascript显示出更多/更少的问题

时间:2019-09-26 19:32:05

标签: javascript html css

当文本最小化到768px或以下时,我有一个“显示更多/更少”按钮。

调整大小时,将通过媒体查询来缩短文本,并使按钮可见。当页面再次扩展到768px以上时,该按钮将隐藏,并再次显示全文。

我的问题是,如果我将尺寸调整为小于768px,并且实际上将功能执行为“显示更多”然后再次“显示更少”,则在扩展窗口(处于缩短状态)时,仅显示缩短的文本,并且为了使全文可见,我必须在扩展窗口之前再次单击“阅读更多”。

即使在按下按钮执行功能并在缩短文本时将其展开后,如何获得此信息:无论以前处于什么状态,都将显示全文?

希望不要太困惑!

function myFunction() {
  let dots = document.getElementById("dots");
  let moreText = document.getElementById("more");
  let btnText = document.getElementById("myBtn");
  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
<p>
  It was akin to an early phase of one of Jose Mourinho's exit strategies as Pochettino told how he had seen these issues looming from afar and how his players must re-establish their 'mental connection' and 'togetherness'. <span id="dots">...</span>  <span id="more"> Thoughts flicked to Christian Eriksen and Toby Alderweireld, who are running down the final year of their contracts to secure lucrative free transfers next summer. Players inside the camp with ambitions elsewhere will certainly eat away at Pochettino.</span>
</p>
<button onclick="myFunction()" id="myBtn">Read more</button>

1 个答案:

答案 0 :(得分:0)

当用户调整窗口大小并添加/删除用于显示/隐藏查询中的文本的CSS类时,可以使用window resize事件来触发函数。希望对您有所帮助。