2015-04-01 79 views
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; 
} 

}); 

回答

2
el.innerHTML += el.innerHTML + '...'; 

的錯誤是在上述line.You're添加el.innerHTML兩次。首先,您將其與...一起添加,然後將其與自身相加,因爲速記+=運算符。

這應該只是

el.innerHTML += '...'; 

這是目前在多個地方,你可能需要編輯所有這些。