问题描述
我尝试过的示例给出了[object NodeList]。 所以我想做的是截断文本段落,以便我可以添加显示更多按钮以显示其余文本。
var testimonialFeedback = document.querySelectorAll('.expanded-text');
var testimonialArray = [...testimonialFeedback];
function ellipsify () {
if (testimonialFeedback.length > 100) {
return (testimonialFeedback.substring(0,100) + "...");
}
else {
return testimonialFeedback;
}
}
testimonialArray.forEach(e => {
e.textContent = ellipsify(testimonialFeedback.textContent);
});
解决方法
您忘记了函数参数。
const testimonialFeedback = document.querySelectorAll('.expanded-text');
const testimonialArray = [...testimonialFeedback];
const testimonialFeedbackMaxLength = 100;
function ellipsify (testimonialFeedback) {
if (testimonialFeedback.length > testimonialFeedbackMaxLength) {
testimonialFeedback = testimonialFeedback.substring(0,testimonialFeedbackMaxLength) + "...";
}
return testimonialFeedback;
}
testimonialArray.forEach(e => {
e.textContent = ellipsify(e.textContent);
});
.expanded-text {
border: 1px solid grey;
}
<div class="expanded-text">Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="expanded-text">Lorem ipsum dolor sit amet,sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="expanded-text">Lorem ipsum dolor sit amet</div>
P.S。使用文本溢出CSS更容易。
.expanded-text {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
border: 1px solid grey;
}
<div class="expanded-text">Lorem ipsum dolor sit amet,sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="expanded-text">Lorem ipsum dolor sit amet</div>