此示例显示/隐藏文本 http://codepen.io/svinkle/pen/AqwDu是我打算在我的网站中进行调整的内容,但是如何修复代码以便不重复段落的第一行? 在示例中,文本以“Lorem ipsum dolor sat amet, consectetur adipiscing elit.Vestibulum facilisnim Want molestie”开头,在 3 点之前刚刚重复过 (...) 如何修复它?
// 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;
}
});
最佳答案
el.innerHTML += el.innerHTML + '...';
错误出现在上面的行中。您添加了 el.innerHTML
两次。首先,您使用 ...
添加它,然后由于简写 +=
运算符而将其与自身添加。
应该是这样
el.innerHTML += '...';
它存在于多个位置,您可能需要编辑所有这些位置。
关于javascript - 显示/隐藏文本 JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29382296/