【发布时间】:2019-07-08 00:21:05
【问题描述】:
我想截断具有相同类名的多个 div,目前我只能让它在第一次出现的 div 上工作
我想截断具有相同类名的多个 div,目前我只能让它在第一次出现的 div 上工作,而不是分别在每个 div 上工作。
var truncate = function (elem, limit, after) {
if (!elem || !limit) return;
var content = elem.textContent.trim();
content = content.split(' ').slice(0, limit);
content = content.join(' ') + (after ? after : '');
elem.textContent = content;
};
var elem = document.querySelector('.truncate');
truncate(elem, 20, '...');
<div class="truncate">
Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>
<div class="truncate">
Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>
【问题讨论】:
标签: javascript html