什么是扩展阅读更多的jQuery代码?

时间:2012-02-22 22:07:59

标签: javascript jquery html css

我想在一个页面上有很多段落。每个段落适用于不同的作者,阅读更多。如果他们点击阅读更多或在段落内,我想隐藏/淡化所有其他段落并扩展他们点击的那个。

用于执行此类操作的jQuery代码是什么?

感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

这是一种方法,无需在段落中添加任何标记。

HTML:

​<div id="content">
  <p>content_here</p>
  <p>content_here</p>
  <p>content_here</p>
  <p>content_here</p>
​</div>​​​​​​​

你会想要一些像这样的CSS:

.dorsal { display: none; }

接下来,JavaScript:

​$('#content').find('p').html( function(){ // for every paragraph in container
   var exposer = '<a href="#" class="expose">More...</a>', // link to insert
       content = $(this).html().split(''),
       cutLength = 50, // choose the cutoff point
       anterior = content.slice( 0,cutLength ).join(''),
       dorsal = content.slice( cutLength ).join(''),
       joined = 
           anterior 
         + exposer 
         + '<span class="dorsal">' 
         + dorsal 
         + '</span>'; // assemble the new contents
    return joined;
})
.on('click','.expose',function(e){
   e.preventDefault();
   var $thisp = $(this).closest('p');
   $('#content').find('p').not( $thisp ).hide(); // hide others
   $thisp             // for the enclosing paragraph
     .find('.dorsal') // select the hidden piece
     .show()          // show it
     .end()           // back to the paragraph
     .find('.expose') // find the "show more" link
     .hide();         // hide it
});​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

您需要在$(document).ready()处理程序中使用此功能。

正如其他人指出的那样,有很多插件可以做这种事情。但有时候自己解决这个问题很有用。

重新折叠和曝光原始段落留作练习。

以下是一个示例:http://jsfiddle.net/redler/wAY8g/1/


根据Ibanez的评论

更新以支持多个段落组:

$('#content').find('div').prepend(function() {
  var exposer = '<a href="#" class="expose">More...</a>',
    rawcontent = $(this).text(),
    cutLength = 100,
    abstract = rawcontent.split('').slice(0, cutLength).join(''),
    abbreviated = '<span class="abstract">' + abstract + exposer + '</span>';
  return abbreviated;
}).end().on('click', '.expose', function(e) {
    e.preventDefault();
    var $thisgroup = $(this).closest('div');
    $('#content').children('div').not($thisgroup).hide(); // hide others
    $thisgroup
      .find('p').show()
      .parent()
      .append('<a href="#" class="showall">Show all</a>')
      .end()
      .closest('div').find('.abstract').hide();
}).on('click', '.showall', function() {
    $(this).remove();
    $('#content').find('div').show().end()
        .find('p:visible').hide().end()
        .find('.abstract').show();
});​

为了实现这一点,我们现在从通过css隐藏的所有段落开始,脚本在加载时构建并显示摘要。还更新了提供重新显示原始状态的链接。

示例:http://jsfiddle.net/ZRB92/1/

答案 1 :(得分:1)

让这个插件为您处理困难的部分:

http://plugins.learningjquery.com/expander/

答案 2 :(得分:1)

<div id="sample_1">
    paragraph sample
    <br><a href="javascript: void(0)" onClick="hide_all_pars('par_1')">read more</a>
    <div id="par_1" style="display: none;">
       Whole paragraph
    </div>
</div>

<div id="sample_2">
    paragraph sample 2
    <br><a href="javascript: void(0)" onClick="hide_all_pars('par_2')">read more</a>
   <div id="par_2" style="display: none;">
       Whole paragraph 2
    </div>
</div>

使用Javascript:

<script type="text/javascript">
    function hide_all_pars(par){
        var i=0;            
        for(i=0;i<=2;i++){
            $('#par_'+i).fadeOut('slow');
        }
        $('#'+par).fadeIn('slow');
    }
</script>

for循环中的2将被替换为你有多少个parahgraph

答案 3 :(得分:0)

我之所以这样写是因为上面的内容并没有完全满足我的要求。这是一些jQuery代码,可为至少包含1个段落的部分添加更多内容。它允许其他元素,例如标题。它旨在隐藏第一段之后的内容,或者如果第一段很长,则将其在定义的点处切掉。它还具有最小化按钮。

if ($('.contentDiv').find('p').length) {

  $(".contentDiv").each(function(i) {

    var splitFirstPara = '300';
    var maxFirstParaLength = '350';
    var firstPara = $(this).find('p').first().text();
    var firstParaLength = firstPara.length;


    if (firstParaLength > maxFirstParaLength) {

      var frontSentence = firstPara.split('').slice(0, splitFirstPara).join('');
      var endSentence = firstPara.split('').slice(splitFirstPara, ).join('');
      var newSentence = '<p>' + frontSentence + '<button class="readMore" data-toggleShow="' + i + '">read more...</button><span class="toggleShow" data-toggleShow="' + i + '" style="display:none;">' + endSentence + '</span></p>';

      $(this).find('p').first().replaceWith(newSentence);
      $(this).find('p').first().nextAll().addClass('toggleShow').attr('data-toggleshow', i).hide();

    } else {

      $(this).find('p').first().nextAll().addClass('toggleShow').attr('data-toggleshow', i).hide();
      $(this).find('p').first().after('<button class="readMore" data-toggleShow="' + i + '">read more</button>');

    }

    $(this).append('<button class="minimise" data-toggleShow="' + i + '" style="display:none;">minimise</button>');

  });

  $("button.readMore").click(function() {

    var sameSectionItems = $(this).attr('data-toggleshow');

    $(this).hide();
    $('.toggleShow[data-toggleshow="' + sameSectionItems + '"]').fadeIn();
    $('.minimise[data-toggleshow="' + sameSectionItems + '"]').fadeIn();


  });

  $("button.minimise").click(function() {

    var sameSectionItems = $(this).attr('data-toggleshow');

    $(this).hide();
    $('.toggleShow[data-toggleshow="' + sameSectionItems + '"]').fadeOut();
    $('.readMore[data-toggleshow="' + sameSectionItems + '"]').fadeIn();

  });

}
.container {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  width: 100%;
  max-width: 800px;
  margin: auto;
}

button.minimise,
button.readMore {
  background: none;
  color: inherit;
  border: none;
  padding: 0;
  font: inherit;
  cursor: pointer;
  outline: inherit;
  text-decoration: underline;
}

p>button.readMore {
  display: inline;
  margin-left: 0.2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <div class="container">
    <div class="contentDiv">
      <h2>Heading Section 1</h2>
      <h3>The first paragraph below is long, <br/>so the read more chops the paragraph and puts the 'read more' inline.</h3>
      <p>I'm baby air plant scenester humblebrag stumptown, banh mi godard shaman fanny pack waistcoat retro cred hoodie messenger bag blue bottle etsy. Pabst plaid literally craft beer actually coloring book vegan shoreditch flannel kickstarter pork belly
        man braid celiac twee intelligentsia. Activated charcoal food truck raw denim, normcore ennui gentrify disrupt salvia brunch lo-fi air plant literally vice iceland woke. Plaid woke knausgaard trust fund thundercats glossier. Schlitz tilde tumblr
        bespoke chartreuse health goth wolf selvage. Retro iceland ethical, gastropub shoreditch four loko 8-bit roof party direct trade.</p>
      <p>Palo santo ethical health goth, affogato neutra you probably haven't heard of them small batch echo park photo booth man braid. Food truck godard beard shaman austin jianbing hot chicken XOXO af mumblecore pork belly meditation. Kickstarter brooklyn
        VHS DIY man bun. Retro venmo fanny pack banjo post-ironic.</p>
      <p>Normcore art party vaporware, jianbing austin truffaut succulents lyft slow-carb wolf bitters. Lo-fi shaman microdosing hashtag. Offal church-key pickled fingerstache tacos subway tile XOXO whatever yr. Ethical drinking vinegar readymade irony,
        marfa offal kickstarter.</p>
    </div>

    <div class="contentDiv">
      <h2>Heading Section 2</h2>
      <p>Palo santo ethical health goth, affogato neutra you probably haven't heard of them small batch echo park photo booth man braid. Food truck godard beard shaman austin jianbing hot chicken XOXO af mumblecore pork belly meditation. Kickstarter brooklyn
        VHS DIY man bun. Retro venmo fanny pack banjo post-ironic.</p>
      <p>Normcore art party vaporware, jianbing austin truffaut succulents lyft slow-carb wolf bitters. Lo-fi shaman microdosing hashtag. Offal church-key pickled fingerstache tacos subway tile XOXO whatever yr. Ethical drinking vinegar readymade irony,
        marfa offal kickstarter.</p>
      <p>Whatever hella hexagon, williamsburg artisan twee wayfarers palo santo shabby chic yr vice pickled wolf. DIY listicle food truck messenger bag lo-fi, la croix offal roof party flannel asymmetrical hoodie trust fund. Fingerstache YOLO messenger bag,
        photo booth shaman normcore iceland austin sartorial copper mug. Organic bespoke mlkshk readymade. XOXO cardigan neutra deep v scenester air plant venmo crucifix chambray gochujang brunch truffaut everyday carry vinyl banh mi.</p>
    </div>
  </div>
</section>