jQuery阅读更多/阅读更少基于</p> <div>中的子<p>使用show();隐藏();和size(); </div>

时间:2014-01-31 13:25:56

标签: jquery html show-hide

我使用jQuery创建了一个脚本,它显示并隐藏div中的第一段以外的所有内容,以提供Read More / Read Less效果。它的基本功能是:

  • 最初在.description div
  • 中隐藏除第一个p之外的所有内容
  • 如果div中有超过1 p,则显示“阅读更多”按钮
  • 在点击时阅读更多内容时显示所有段落,同时替换 阅读更多按钮,阅读少按钮
  • 隐藏除第一段以外的所有内容,并将read less替换为read more 点击“阅读更少”时

您可以在此处查看此脚本: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很新),或者是否有更有效的方法可以获得相同的结果?

非常感谢

3 个答案:

答案 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();
});

小提琴:http://jsfiddle.net/praveenscience/SZLgs/