【问题标题】:What is the jQuery code to Expand a Read More?扩展阅读器的 jQuery 代码是什么?
【发布时间】:2020-12-11 17:03:08
【问题描述】:

我想在一个页面上有很多段落。每个段落都针对不同的作者,并阅读更多内容。如果他们点击阅读更多或段落内我想隐藏/淡出所有其他段落并展开他们点击的段落。

做这种事情的 jQuery 代码是什么?

感谢您的帮助。

【问题讨论】:

  • 你可以使用 jQueryUI 的手风琴 jqueryui.com/demos/accordion
  • 我们可能需要一个小的代码示例,但 Sotiris 和 dragon 是对的 - 使用手风琴或其他插件。您将节省时间和精力。

标签: javascript jquery html css


【解决方案1】:

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

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/

【讨论】:

  • Ken,这仅适用于每个主题有一个段落。看看当您为每个主题添加更多段落时会发生什么。
  • @Ibanez,我同意,但你的问题规定了每个作者只有一个段落的狭隘情况。正如您所暗示的,如果您想处理多个段落的组,则每个“故事”周围都必须有一个额外的容器。毕竟,代码如何知道哪些段落构成一个组?额外的分组层也增加了挑战,因为您必须在不破坏封闭段落结构的情况下创建较短的可见摘录。
  • @Ibanez,我们在这里稍微走下兔子洞,但我已经更新了示例以允许按容器 div 对段落进行分组。
  • Ken,这与我正在寻找的非常接近。我看到一些不适用于我的布局的问题。我以个人图像开始每个段落,并为段落的第一个字母加上首字母下沉。在单击它之前,我正在丢失首字母下沉的图像和跨度标签。我还想知道如何更改 cutLength 发生的位置。这是在没有完成单词的情况下切断单词。有没有办法告诉它在哪里进行剪切并在每个段落的不同点进行剪切?非常感谢。
  • @Ibanez,这里有一些简化,因为它只说明了一种一般方法。首先,“摘要”是使用每个部分的纯文本构建的(参见rawcontent)。这就是为什么你的帽子和其他元素不是抽象的。至于尊重单词边界——这确实可以做到。您将用一个检查候选切割点的函数替换静态切割长度值,检查它是否是一个空间,如果不是,则向后走直到找到一个空间;然后将其作为实际切割点返回。如果你做了所有这些,当然,你基本上已经编写了一个功能齐全的插件。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    <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 将替换为您拥有的段落数

    【讨论】:

    • 这不是我的想法。您的示例仅扩展了该段落并将其下的其他作者下推。
    • 对不起,我还没有理解你的问题 :) 也许其他人可以提供帮助;)
    【解决方案4】:

    我写这个是因为上面没有完全符合我的要求。这是一些 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2013-02-27
      • 2011-06-12
      • 2017-08-24
      相关资源
      最近更新 更多