2015-04-01 91 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 += '...'; 

这是目前在多个地方,你可能需要编辑所有这些。