如何使用jQuery显示和隐藏按钮read more
。我不知道如何选择全文长度并检查是否需要阅读更多"按钮与否。我限制了1000个符号的示例,之后显示了按钮read more
例如我有一个帖子并且:
Lorem ipsum dolor sit amet, consectetur adipisicing 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... (read more) when click and I can see full text
但是,如果我的名称少于1000个符号,我想说我不需要"阅读更多"这个限制中的文本长度并不是必需的,并且"阅读更多"按钮。需要隐藏。 谢谢!
答案 0 :(得分:0)
试试这个:
html:
<div class="more"> a lot of text </div>
js:
$(function(){
var showChar = 130;
var ellipsestext = "...";
var moretext = "more";
var lesstext = "less";
$('.more').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar-1);
var h = content.substr(showChar-1, content.length - showChar);
var html = c + '<span class="moreellipses">' + ellipsestext+ ' </span><span class="morecontent"><span>' + h + '</span> <a href="" class="morelink">' + moretext + '</a></span>';
$(this).html(html);
}
});
$(".morelink").click(function(){
if($(this).hasClass("less")) {
$(this).removeClass("less");
$(this).html(moretext);
} else {
$(this).addClass("less");
$(this).html(lesstext);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
});
但是:我无法完成代码,js中有小错误,请进一步处理。我现在需要学习考试..抱歉
这是jsfiddle:http://jsfiddle.net/CbLbu/
答案 1 :(得分:0)
您也可以尝试实现此代码:
(function ($) {
var _text = [],
getText = function () {
var div = $(this), text = div.text(), textLength = text.length, full, short;
if (textLength > 100) {
full = text;
short = text.substr(0, 100);
div.html(short + '... <span class="read-link read-more">read more</span>');
} else full = text;
_text.push({ full: full, short: short});
};
$('div').each(getText);
$('div').on('click', '.read-link', function (index) {
var span = $(this), div = span.parent();
if (span.hasClass('read-more')) div.html(_text[div.index()].full + '... <span class="read-link read-less">read less</span>');
else div.html(_text[div.index()].short + '... <span class="read-link read-more">read more</span>');
});
})(jQuery);
答案 2 :(得分:0)
如果您有更多卡片带文字:
var _text = [],
getText = function () {
var div = $(this), text = div.text(), textLength = text.length, full, short;
if (textLength > 172) {
full = text;
short = text.substr(0, 172);
div.html(short + '... <span class="read-link read-more" ' +
'style ="color:#1976D2">(more)</span>');
} else full = text;
_text.push({full: full, short: short});
};
$('.more').each(getText).on('click', '.read-link', function (index) {
var span = $(this), div = span.parent();
var index = $(this).closest('.questions-list__card').index();
if (span.hasClass('read-more')) div.html(_text[index].full + '... <span class="read-link read-less" style ="color:#1976D2">read less</span>');
else div.html(_text[index].short + '... <span class="read-link read-more" ' +
'style ="color:#1976D2">(more)</span>');
});
});