使用javascript隐藏/显示文本?

我在尝试切换文本时遇到问题。我有一个被截断的文本,如何在单击按钮时在截断文本和原始文本之间来回切换?

var myButton = document.getElementById('toggle_text')

var text = document.getElementById('original_text')

console.log(text)


var truncate = function(elem, limit, after) {


  // Make sure an element and number of items to truncate is provided

  if (!elem || !limit) return;


  // Get the inner content of the element

  var content = elem.textContent.trim();


  // Convert the content into an array of words

  // Remove any words above the limit

  content = content.split(' ').slice(0, limit);


  // Convert the array of words back into a string

  // If there's content to add after it, add it

  content = content.join(' ') + (after ? after : '');


  // Inject the content back into the DOM

  elem.textContent = content;


};


var elem = document.querySelector('.truncate');

truncate(elem, 7, '...');



function switchText() {


}

<div class="truncate" id="original_text">

  Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.

</div>


<div>

  <button id="toggle_text" onClick='switchText()'>Toggle Between truncate and Original Text</button>

</div>


叮当猫咪
浏览 142回答 3
3回答

MM们

我会考虑查看S.Serpooshan对类似问题的回答。通常,这可以仅使用 CSS 来完成,并且将是维护页面状态的更好方法。不必将文本作为变量存储在 JS 中,它可以从 DOM 流中隐藏,但仍然可以轻松访问。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript