我现在有一个jQuery片段,当子字符串大于父容器时,它成功地截断了我的文本(参见下面)。
var initial = $('.js-text').text();
$('.js-text').text(initial);
while($('.js-text').outerHeight() > $('.js-text-truncator').height()) {
$('.js-text').text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}我使用了我所拥有的语义,就像我计划在现有标记中的多个位置使用这个小jQuery组件一样:
<div class="existing-first-div-container js-text-truncator">
<p class="existing-first-string js-text">The quick brown fox</p>
</div>
<div class="existing-second-div-container js-text-truncator">
<p class="existing-second-string js-text"> jumped over the lazy red dog.</p>
</div>如果你读了这么多而且已经猜到了我的问题.
所以问题是,我的jQuery正在存储文本,但是它存储了所有的文本。所以这两个现存的div都被截断了,但最后都读到了“快速的棕色狐狸跳过那只懒惰的红狗。”而不是一读“快褐狐狸”和二读“跳过懒惰的红狗”。
是否可以以我想要的方式使用我的作为标记的扩展,而不同时存储所有截断的文本实例?
发布于 2015-10-12 11:27:36
.text清楚地指出
获取匹配元素集中的每个元素的组合文本内容,包括它们的后代,或者设置匹配元素的文本内容。
有了.js-text的元素集之后,对它们执行一个.each,然后分别获取、截断和设置.text。
如果您希望在窗口重新大小时重新运行,我建议您通过超时(因此,代码运行后,窗口停止调整至少400 at )。如果没有这个解决办法,它往往会对性能造成很大的影响。
var resizeTimeout = false;
$(window).resize(onWindowResize); // bind resize event.
trimAllText(); //run once at start.
function onWindowResize() {
if(resizeTimeout){
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(function(e){
resizeTimeout = false;
// this is code that is ran at the "end" of a resize.
trimAllText();
}, 400);
}
function trimAllText(){
var initialElements = $('.js-text');
initialElements.each(function(){
var elem = $(this);
while(elem.outerHeight() > elem.closest('.js-text-truncator').height()) {
elem.text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
});
});
}https://stackoverflow.com/questions/33079894
复制相似问题