jQuery 如何在一定长度内隐藏/显示更多文本(如 youtube)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5270227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:51:16  来源:igfitidea点击:

How to hide/show more text within a certain length (like youtube)

jquery

提问by Ben

I want to have a text to only be a certain amount of characters/length and after that length, I want to put a link to reveal the full length of the text.

我想让一个文本只有一定数量的字符/长度,在这个长度之后,我想放一个链接来显示文本的全长。

The link will be (more...). And once the user clicks the link (more..)the rest of the text will slide down.

该链接将是(more...)。一旦用户单击链接(more..),其余的文本将向下滑动。

How would I accomplish this?

我将如何做到这一点?

Heres an example.

这是一个例子。

blah blah blah blah blah (more...)

When the user clicks (more..), it will show the entire text.

当用户单击 时(more..),它将显示整个文本。

NOTE: I am taking a about data in a table row/table cell, not just any text.

注意:我在表格行/表格单元格中获取关于数据,而不仅仅是任何文本。

回答by amosrivera

The secret about this effect, is wrapping the parts that you want to control with HTML tags.

这个效果的秘密在于用 HTML 标签包裹你想要控制的部分。

$(".more").toggle(function(){
    $(this).text("less..").siblings(".complete").show();    
}, function(){
    $(this).text("more..").siblings(".complete").hide();    
});


<span class="teaser">text goes here</span>

<span class="complete"> this is the 
complete text being shown</span>

<span class="more">more...</span>

Online demo here:http://jsfiddle.net/zA23k/215/

在线演示在这里:http : //jsfiddle.net/zA23k/215/

回答by Hussein

$('#more').click(function(e) {
    e.stopPropagation();
    $('div').css({
        'height': 'auto'
    })
});

$(document).click(function() {
    $('div').css({
        'height': '40px'
    })
})

Check working example at http://jsfiddle.net/7Vv8u/4/

http://jsfiddle.net/7Vv8u/4/检查工作示例

With Animation http://jsfiddle.net/7Vv8u/5/

带动画http://jsfiddle.net/7Vv8u/5/

Click on Read more to expand the text. Click outside to minimize it again.

单击“阅读更多”以展开文本。单击外部以再次将其最小化。

回答by Kate

I know this question is a little old (and has had it's answer selected already) but for those wanting another option that're coming across this question through Google (like I did), I found this dynamic text shortener:

我知道这个问题有点旧(并且已经选择了它的答案)但是对于那些想要通过谷歌遇到这个问题的另一个选项的人(就像我一样),我发现了这个动态文本缩短器:

Dynamically shortened Text with “Show More” link using jQuery

使用 jQuery 使用“显示更多”链接动态缩短文本

I found it was better because you could set the character limit, rather than extra spans in the code, or setting a specific height to a container.
Hope it helps someone else out!

我发现它更好,因为您可以设置字符限制,而不是在代码中设置额外的跨度,或者为容器设置特定的高度。
希望它可以帮助别人!

回答by Aram

If you need some complete solution, you can use this :

如果你需要一些完整的解决方案,你可以使用这个:

http://jsfiddle.net/7Vv8u/2703/

http://jsfiddle.net/7Vv8u/2703/

JS (jQuery)

JS (jQuery)

var text = $('.text-overflow'),
     btn = $('.btn-overflow'),
       h = text.scrollHeight; 

if(h > 120) {
    btn.addClass('less');
    btn.css('display', 'block');
}

btn.click(function(e) 
{
  e.stopPropagation();

  if (btn.hasClass('less')) {
      btn.removeClass('less');
      btn.addClass('more');
      btn.text('Show less');

      text.animate({'height': h});
  } else {
      btn.addClass('less');
      btn.removeClass('more');
      btn.text('Show more');
      text.animate({'height': '120px'});
  }  
});

HTML

HTML

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<div class="text-overflow">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<a class="btn-overflow" href="#">Show more</a> 

CSS

CSS

.text-overflow {
  width:250px;
  height:120px;
  display:block; 
  overflow:hidden;
  word-break: break-word;
  word-wrap: break-word;
}

.btn-overflow {
  display: none;
  text-decoration: none; 
}

回答by Trevor Nestman

Show More, Show Less (Only when needed) No JQuery

显示更多,显示更少(仅在需要时)没有 JQuery

I needed this functionality for an RSS feed on our company's website. This is what I came up with:

我需要此功能用于我们公司网站上的 RSS 提要。这就是我想出的:

// Create Variables
var allOSB = [];
var mxh = '';

window.onload = function() {
  // Set Variables
  allOSB = document.getElementsByClassName("only-so-big");
  
  if (allOSB.length > 0) {
    mxh = window.getComputedStyle(allOSB[0]).getPropertyValue('max-height');
    mxh = parseInt(mxh.replace('px', ''));
    
    // Add read-more button to each OSB section
    for (var i = 0; i < allOSB.length; i++) {
      var el = document.createElement("button");
      el.innerHTML = "Read More";
      el.setAttribute("type", "button");
      el.setAttribute("class", "read-more hid");
      
      insertAfter(allOSB[i], el);
    }
  }

  // Add click function to buttons
  var readMoreButtons = document.getElementsByClassName("read-more");
  for (var i = 0; i < readMoreButtons.length; i++) {
    readMoreButtons[i].addEventListener("click", function() { 
      revealThis(this);
    }, false);
  }
  
  // Update buttons so only the needed ones show
  updateReadMore();
}
// Update on resize
window.onresize = function() {
  updateReadMore();
}

// show only the necessary read-more buttons
function updateReadMore() {
  if (allOSB.length > 0) {
    for (var i = 0; i < allOSB.length; i++) {
      if (allOSB[i].scrollHeight > mxh) {
        if (allOSB[i].hasAttribute("style")) {
          updateHeight(allOSB[i]);
        }
        allOSB[i].nextElementSibling.className = "read-more";
      } else {
        allOSB[i].nextElementSibling.className = "read-more hid";
      }
    }
  }
}

function revealThis(current) {
  var el = current.previousElementSibling;
  if (el.hasAttribute("style")) {
    current.innerHTML = "Read More";
    el.removeAttribute("style");
  } else {
    updateHeight(el);
    current.innerHTML = "Show Less";
  }
}

function updateHeight(el) {
  el.style.maxHeight = el.scrollHeight + "px";
}

// thanks to karim79 for this function
// http://stackoverflow.com/a/4793630/5667951
function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
@import url('https://fonts.googleapis.com/css?family=Open+Sans:600');

*,
*:before,
*:after {
  box-sizing: border-box;
}
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  width: 100%;
}
body {
  font-family: 'Open Sans', sans-serif;
}
h1 {
  text-align: center;
}
.main-container {
  margin: 30px auto;
  max-width: 1000px;
  padding: 20px;
}
.only-so-big p {
  padding: 0;
  margin: 0;
}
p {
  font-size: 15px;
  line-height: 20px;
}
hr {
  background: #ccc;
  display: block;
  height: 1px;
  width: 100%;
}


/*
  NECESSARY SECTION
*/
.only-so-big {
  background: rgba(178, 252, 255, .3);
  height: 100%;
  max-height: 100px;
  overflow: hidden;
  -webkit-transition: max-height .75s;
  transition: max-height .75s;
}

.read-more {
  background: none;
  border: none;
  color: #1199f9;
  cursor: pointer;
  font-size: 1em;
  outline: none; 
}
.read-more:hover {
  text-decoration: underline;
}
.read-more:focus {
  outline: none;
}
.read-more::-moz-focus-inner {
  border: 0;
}
.hid {
  display: none;
}
<div class="main-container">
      <h1>Controlling Different Content Size</h1>
      <p>We're working with an RSS feed and have had issues with some being much larger than others (content wise). I only want to show the "Read More" button if it's needed.</p>
      <div class="only-so-big">
        <p>This is just a short guy. No need for the read more button.</p>
      </div>
      <hr>
      <div class="only-so-big">
        <p>This one has way too much content to show. Best be saving it for those who want to read everything in here.</p>
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
          voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi THE END!</p>
      </div>
      <hr>
      <div class="only-so-big">
        <p>Another small section with not a lot of content</p>
      </div>
      <hr>
      <div class="only-so-big">
        <p>Make Window smaller to show "Read More" button.<br> totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed?</p>
      </div>
    </div>

回答by Stanley Umeanozie

For those who just want a simple Bootstrap solution.

对于那些只想要一个简单的 Bootstrap 解决方案的人。

    <style>
     .collapse.in { display: inline !important; }
    </style>

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the
    <span class="collapse" id="more">
      1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    </span>
    <span><a href="#more" data-toggle="collapse">... <i class="fa fa-caret-down"></i></span>

Here's a CodePen example.

这是一个CodePen 示例

Remember to include jqueryand bootstrap.min.jsin your header.

请记住在标题中包含jquerybootstrap.min.js

If you aren't using fontawesome icons, change <i class="fa fa-caret-down"></i>to any icon of your choice.

如果您不使用 fontawesome 图标,请更改<i class="fa fa-caret-down"></i>为您选择的任何图标。

回答by Rikard

This is another solution using clickable articles (can of course be changed to anything).

这是使用可点击文章的另一种解决方案(当然可以更改为任何内容)。

http://jsfiddle.net/SqJ53/2/

http://jsfiddle.net/SqJ53/2/

Edit: If you want to use CSS animation, you must use MAX-HEIGHT instead of HEIGHT

编辑:如果你想使用 CSS 动画,你必须使用 MAX-HEIGHT 而不是 HEIGHT

Javascript

Javascript

$(".container article").click(function() {
        $(this).toggleClass("expand");
})

CSS

CSS

.container {
    position: relative;
    width: 900px;
    height: auto;
}
.container article {
    position: relative;
    border: 1px solid #999;
    height: auto;
    max-height: 105px;
    overflow: hidden;
    -webkit-transition: all .5s ease-in-out;
    -moz-transition: all .5s ease-in-out;
    transition: all .5s ease-in-out; 
}
.container article:hover {
    background: #dadada;
}
.container article.expand {
    max-height: 900px;
}

HTML

HTML

<div class="container">
    <article class="posts-by-cat_article-222">
        <h3><a href="http://google.se">Section 1</a></h3>
        <p>This is my super long content, just check me out.</p>
        <p>This is my super long content, just check me out.</p>
        <p>This is my super long content, just check me out.</p>
        <p>This is my super long content, just check me out.</p>
    </article>

    <article class="posts-by-cat_article-222">
        <h3><a href="http://google.se">Section 2</a></h3>
        <p>This is my super long content, just check me out.</p>
        <p>This is my super long content, just check me out.</p>
        <p>This is my super long content, just check me out.</p>
        <p>This is my super long content, just check me out.</p>

    </article>
</div>

回答by Mike

Here's a really simple solution that worked for me,

这是一个对我有用的非常简单的解决方案,

<span id="text">Extra Text</span>
<span id="more">show more...</span>
<span id="less">show less...</span>

<script>
 $("#text").hide();
 $("#less").hide();
 $("#more").click( function() {
   $("#text").show();
   $("#less").show();
   $("#more").hide();
 });
 $("#less").click( function() {
   $("#text").hide();
   $("#less").hide();
   $("#more").show();
 });
</script>

回答by Parvesh Kumar Tandon

Another possible solution that we can use 2 HTML element to store brief and complete text. Hence we can show/hide appropriate HTML element :-)

另一种可能的解决方案是我们可以使用 2 个 HTML 元素来存储简短和完整的文本。因此我们可以显示/隐藏适当的 HTML 元素 :-)

<p class="content_description" id="brief_description" style="display: block;"> blah blah blah blah blah  </p><p class="content_description" id="complete_description" style="display: none;"> blah blah blah blah blah with complete text </p>

/* jQuery code to toggle both paragraph. */

(function(){
        $('#toggle_content').on(
                'click', function(){
                                $("#complete_description").toggle();
                                $("#brief_description").toggle();
                                if ($("#complete_description").css("display") == "none") {
                                    $(this).text('More...');
                                }   else{
                                    $(this).text('Less...');
                                }
                        }
                );
    })();

回答by realmag777

So much answers and all them good, but I will suggest my own, maybe it will be usefull for somebody.

这么多答案,所有答案都很好,但我会建议我自己的,也许对某人有用。

We have HTML in the template:

我们在模板中有 HTML:

<div class="listing-item-excerpt" id="listing-item-excerpt-<?= $task['id'] ?>">
    <?= mb_substr($txt, 0, 150) ?><span class="complete_txt"><?= mb_substr($txt, 150) ?></span>
    <a href="javascript: show_more_less(<?= $task['id'] ?>);void(0);" class="more_less_btn" data-more-txt="<?= __('... show more') ?>" data-less-txt="&nbsp;<?= __('show less') ?>" data-state="0"><?= __('... show more') ?></a>
</div>

JS function for toggling which:

用于切换的 JS 函数:

function show_more_less(task_id) {

    var btn = jQuery('#listing-item-excerpt-' + task_id).find('.more_less_btn');
    var txt_container = jQuery('#listing-item-excerpt-' + task_id).find('.complete_txt');
    var state = parseInt(jQuery(btn).data('state'), 10);
    if (state === 0) {
        jQuery(txt_container).show();
        jQuery(btn).text(jQuery(btn).data('less-txt'));
        jQuery(btn).data('state', 1);
    } else {
        jQuery(txt_container).hide();
        jQuery(btn).text(jQuery(btn).data('more-txt'));
        jQuery(btn).data('state', 0);
    }
}