JQuery更多/更少切换

时间:2013-10-13 09:35:17

标签: jquery

我拼凑了下面的切换,以显示第一段中第一段有更多按钮作为跨度。当点击更多时,会显示其他段落并且隐藏更多按钮,但是当点击较少按钮时,我需要更多按钮才能返回..你能帮忙吗?

   <script>
    $('div#introduction').each(function(){
     var NODES = $(this).find('p').length;
     if(NODES>0){
      $(this).find('p:first').addClass('first');
      $(this).find('p:last').addClass('last');
      $('#introduction p.first').append('&nbsp;<span class="more"><a class="toggle">More</a></span>');
      $('#introduction p.last').append('&nbsp;<span class="less"><a class="toggle">less</a></span>');
      $('#introduction p').hide().slice(0,1).addClass('fixed').show();
      $('.toggle').click(function(){
       $( ".more" ).hide();
       $('p:not(.toggle,.fixed)').toggle();
       $(this).text(function(_, ML){
        return ML === 'Less' ? 'More' : 'Less';
       });
      });
     }
    });
   </script>

非常感谢提前

斯图

2 个答案:

答案 0 :(得分:3)

取代它是不够的:

$( ".more" ).hide();

用这个:

$( ".more" ).toggle();

...然后删除更改文本的代码,以使您的点击处理程序最终结束:

  $('.toggle').click(function(){
     $( ".more" ).toggle();
     $('p:not(.toggle,.fixed)').toggle();
  });

演示:http://jsfiddle.net/dXJrr/

从那以后,你所做的只是切换你可以将点击处理程序减少到一行的东西:

      $('.more, p:not(.toggle,.fixed)').toggle();

......虽然你可以得到更漂亮的效果:

     $('.more').toggle();
     $('p:not(.toggle,.fixed)').slideToggle();

演示:http://jsfiddle.net/dXJrr/2/

答案 1 :(得分:1)

如果我的理解是正确的,以下是您的需要。

  $('div#introduction').each(function () {
      var NODES = $(this).find('p').length;
      if (NODES > 0) {
          $(this).find('p:first').addClass('first');
          $(this).find('p:last').addClass('last');
          $('#introduction p.first').append('&nbsp;<span class="more"><a class="toggle">More</a></span>');
          $('#introduction p.last').append('&nbsp;<span class="less"><a class="toggle">Less</a></span>');
          $('#introduction p').hide().slice(0, 1).addClass('fixed').show();
          $('.more').click(function () {
              $('p:not(.toggle,.fixed)').toggle();
              $(".less").show();
              $(".more").hide();
          });
          $('.less').click(function () {
              $('p:not(.toggle,.fixed)').toggle();
              $(".more").show();
              $(".less").hide();
          });
      }
  });

Demo Fiddle

相关问题