我使用jQuery创建了一个脚本,它显示并隐藏div中的第一段以外的所有内容,以提供Read More / Read Less效果。它的基本功能是:
您可以在此处查看此脚本:http://jsfiddle.net/0li4tw/Nv27E/
paragraphCount = $(".description > p").size();
$("#hider").hide();
$("#shower").hide();
if (paragraphCount > 1) {
$("#shower").show();
}
$( "#hider" ).click(function() {
$(".description p").not(":first").hide();
$("#hider").hide();
$("#shower").show();
});
$( "#shower" ).click(function() {
$(".description p").show();
$("#shower").hide();
$("#hider").show();
});
$(".description p").not(":first").hide();
脚本是否有任何明显的问题 - 特别是浏览器相关(我对jquery / javascript很新),或者是否有更有效的方法可以获得相同的结果?
非常感谢
答案 0 :(得分:2)
我会使用某些东西来定位所有描述,并将所有可切换内容包装在容器中,以防我想做其他事情,而不仅仅是切换/隐藏它们(可能是效果?)。
$('.description').each(function() {
// if there are more than just one P
if ( $(this).children('p').length > 1 ) {
// wrap them in a container & also have class .hidden (hides content)
$('p:not(:first-child)').wrapAll('<div class="descr-extended hidden"></div>');
}
});
$('.descr-toggler').on('click', function() {
$('.descr-extended').toggleClass('hidden'); // toggling visibility w .hidden
});
更多 - &gt; http://jsfiddle.net/0li4tw/Nv27E/
改进:使用一些相关性按钮“prev('。desc-extended')”(并且只有在隐藏内容时才从脚本添加按钮)
答案 1 :(得分:0)
有效。您可以使用toggle()在显示时隐藏,并在隐藏时显示。它会减少你的代码:
paragraphCount = $(".description > p").size();
$("#hider").hide();
$("#shower").hide();
if (paragraphCount > 1) {
$("#shower").show();
}
$( "#hider, #shower" ).click(function() {
$(".description p").not(":first").toggle();
$("#hider").toggle();
$("#shower").toggle();
});
$(".description p").not(":first").hide();
答案 2 :(得分:-1)
我做了类似的实验。这里面也支持复杂的HTML标签。最好的部分是,它使用data-
属性。
$(document).ready(function(){
length = 200;
cHtml = $(".content").html();
cText = $(".content").text().substr(0, length).trim();
$(".content").addClass("compressed").html(cText + "... <a href='#' class='exp'>More</a>");
window.handler = function()
{
$('.exp').click(function(){
if ($(".content").hasClass("compressed"))
{
$(".content").html(cHtml + "<a href='#' class='exp'>Less</a>");
$(".content").removeClass("compressed");
handler();
return false;
}
else
{
$(".content").html(cText + "... <a href='#' class='exp'>More</a>");
$(".content").addClass("compressed");
handler();
return false;
}
});
}
handler();
});