0
此示例顯示/隱藏文本http://codepen.io/svinkle/pen/AqwDu是我打算在我的網站上適應的東西,但如何修復代碼以便不重複段落的第一行? 在這個例子中,文字以「Lorem ipsum dolor sit amet,consectetur adipiscing elit。Vestibulum facilisnim想要molestie」開始,它剛剛在3分之前重複(...)如何解決它?顯示/隱藏文本JavaScript錯誤
// Select all text areas
var textArea = document.querySelectorAll('[data-js=content]'),
maxText = 100;
// For each one...
[].forEach.call(textArea, function(el) {
var textAreaLength = el.innerHTML.length,
teaserText = el.innerHTML.substr(0, 100),
fullText = el.innerHTML,
showTeaser = false;
// Check to see if this text length is more
// than the max
if (textAreaLength >= maxText) {
// Set flag
showTeaser = true;
// Set teaser text
el.innerHTML = teaserText;
el.innerHTML += el.innerHTML + '...';
// Create button
var button = document.createElement('button');
button.innerHTML = 'Show More';
button.classList.add('button');
el.appendChild(button);
// Button click event
button.onclick = function() {
if (showTeaser === true) {
// Update flag
showTeaser = false;
// Update button text
this.innerHTML = 'Show Less';
// Show full text
el.innerHTML = fullText;
// Re-append the button
el.appendChild(this);
} else {
// Update flag
showTeaser = true;
// Update button text
this.innerHTML = 'Show More';
// Show teaser text
el.innerHTML = teaserText;
el.innerHTML += el.innerHTML + '...';
// Re-append the button
el.appendChild(this);
}
return false;
};
} else {
// Show full text
el.innerHTML = fullText;
}
});