用jquery重新排列附加的html



我用jquery创建了一个简单的read-more函数,它显示和隐藏超过多个字符的文本。它运行良好,但我使用了一些开源代码,我想进一步了解如何重新排列正在生成的html。首先,我希望按钮位于文本下方。因此,隐藏类的span出现在按钮之前,因此不会将文本拖到单独的行上。我还想添加"…"在此隐藏跨度之前,以及可见文本的末尾。当我尝试移动在类隐藏的情况下附加跨度的行时,此文本将进入按钮内部。

https://jsfiddle.net/w4j5rhme/

jQuery( document ).ready(function() {
jQuery(function () {
var maxL = 150;
jQuery('.outer-card-expand p').each(function () {
var text = jQuery(this).text();
if(text.length > maxL) {
var begin = text.substr(0, maxL),
end = text.substr(maxL);
jQuery(this).html(begin)
.append(jQuery('<div class="see-more see-more-closed"></div>').html(''))
.append(jQuery('<span class="hidden">').html(end))
}
});
jQuery(document).on('click', '.see-more', function () {
jQuery(this).next('.hidden').slideToggle(400);
})        
})
});

首先,这是我在Edge、Firefox和Chrome 中使用的修改后的脚本

jQuery( document ).ready(function() {
jQuery(function () {

var maxL = 150;
jQuery('.outer-card-expand p').each(function () {
var text = jQuery(this).text();
if(text.length > maxL) {
var begin = text.substr(0, maxL),
end = text.substr(maxL);
jQuery(this).html(begin)
.append('<span class="read-more">...</span>')
.append(jQuery('<span class="hidden">').html(end))
.append(jQuery('<div class="see-more see-more-closed"></div>').html(''))
}
});
jQuery(document).on('click', '.see-more', function () {
jQuery('.hidden').slideToggle(400);
jQuery('.read-more').toggle('hidden');
})        
})
});

这两个变化是

  1. 订单链接.append功能已切换,并添加了表示更多文本的跨度

  2. .slideToggle直接应用于隐藏跨度,以及在<span class="read-more">...</span>上切换可见性

最新更新