Dynamically shotened Text with「Show More」link using jQuery

8717 ワード

記事の起源:http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/
Dynamically shotened Text with「Show More」link using jQuery
Update:The plugin now on GitHub:https://github.com/viralpatel/jquery.shorten
Facebook user udates has great functionlity.If the commented is larger than few characters,the extra worlds are hide and a show morement to user.This way you can keep long text Alview the future the stred clopter.
Here is a simple tutoril to achieve this using jQuery/Javascript.
The HTML
Below is the sample text.Each text is wrapped in a DIV.Note that we have added a clast“more”in each div.This class will decide if a text needs to be shotend and show more link show wed or not.
<div class="comment more">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum laoreet, nunc eget laoreet sagittis,
    quam ligula sodales orci, congue imperdiet eros tortor ac lectus.
    Duis eget nisl orci. Aliquam mattis purus non mauris
    blandit id luctus felis convallis.
    Integer varius egestas vestibulum.
    Nullam a dolor arcu, ac tempor elit. Donec.
</div>
<div class="comment more">
    Duis nisl nibh, egestas at fermentum at, viverra et purus.
    Maecenas lobortis odio id sapien facilisis elementum.
    Curabitur et magna justo, et gravida augue.
    Sed tristique pellentesque arcu quis tempor.
</div>
<div class="comment more">
    consectetur adipiscing elit. Proin blandit nunc sed sem dictum id feugiat quam blandit.
    Donec nec sem sed arcu interdum commodo ac ac diam. Donec consequat semper rutrum.
    Vestibulum et mauris elit. Vestibulum mauris lacus, ultricies.
</div>
The CSS
Below is the CSS code for our example.Note the class'.moreontent span's hidden.The extra text from the content is wrapped in this span and is hidden at time of page loading.
a {
    color: #0254EB
}
a:visited {
    color: #0254EB
}
a.morelink {
    text-decoration:none;
    outline: none;
}
.morecontent span {
    display: none;
}
.comment {
    width: 400px;
    background-color: #f0f0f0;
    margin: 10px;
}
 
The Javascript
Below is the Javascript code which iterate through each DIV with class“more”and split the text in two.First half to user and second is made hidden with a link“more.”.
You can change the behaviour by change following js variables.
  • show Char:Total characters to show to user.If the content is more then show Char,it will be split into two halves and first one will be show to user.
  • ellipspestext:The text displayed before“more”link.Default is“…”
  • morretext:The text shown in more link.Default is"more".You can change to">
  • less text:The text shown in less link.Default is"less".You can change to"<"
  • "
    $(document).ready(function() {
        var showChar = 100;
        var ellipsestext = "...";
        var moretext = "more";
        var lesstext = "less";
        $('.more').each(function() {
            var content = $(this).html();
     
            if(content.length > showChar) {
     
                var c = content.substr(0, showChar);
                var h = content.substr(showChar-1, content.length - showChar);
     
                var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
     
                $(this).html(html);
            }
     
        });
     
        $(".morelink").click(function(){
            if($(this).hasClass("less")) {
                $(this).removeClass("less");
                $(this).html(moretext);
            } else {
                $(this).addClass("less");
                $(this).html(lesstext);
            }
            $(this).parent().prev().toggle();
            $(this).prev().toggle();
            return false;
        });
    });
     
    Update
    The above code is modified into jQuery plugin.Also it has now been been hanced.HTML tags are now parsed properly within text to preserve its unifity while shart.Please chect please latest plugn cougn Gron Grom
    https://github.com/viralpatel/jquery.shorten
    jQuery Plugin
    コード
    /*
     * jQuery Shorten plugin 1.0.0
     *
     * Copyright (c) 2013 Viral Patel
     * http://viralpatel.net
     *
     * Dual licensed under the MIT license:
     *   http://www.opensource.org/licenses/mit-license.php
     */
     
     (function($) {
        $.fn.shorten = function (settings) {
         
            var config = {
                showChars: 100,
                ellipsesText: "...",
                moreText: "more",
                lessText: "less"
            };
     
            if (settings) {
                $.extend(config, settings);
            }
             
            $(document).off("click", '.morelink');
             
            $(document).on({click: function () {
     
                    var $this = $(this);
                    if ($this.hasClass('less')) {
                        $this.removeClass('less');
                        $this.html(config.moreText);
                    } else {
                        $this.addClass('less');
                        $this.html(config.lessText);
                    }
                    $this.parent().prev().toggle();
                    $this.prev().toggle();
                    return false;
                }
            }, '.morelink');
     
            return this.each(function () {
                var $this = $(this);
                if($this.hasClass("shortened")) return;
                 
                $this.addClass("shortened");
                var content = $this.html();
                if (content.length > config.showChars) {
                    var c = content.substr(0, config.showChars);
                    var h = content.substr(config.showChars, content.length - config.showChars);
                    var html = c + '<span class="moreellipses">' + config.ellipsesText + ' </span><span class="morecontent"><span>' + h + '</span> <a href="#" class="morelink">' + config.moreText + '</a></span>';
                    $this.html(html);
                    $(".morecontent span").hide();
                }
            });
             
        };
     
     })(jQuery);
     
    Usage
    Step 1:Include the jQuery plugin your HTML
    <script type="text/javascript"
        src="http://viralpatel.net/blogs/demo/jquery/jquery.shorten.1.0.js"></script>
     Step 2:Add the code to shoten any DIV content.In below example we are shotening DIV with clast「coment」.
    <div class="comment">
        This is a long comment text.
        This is a long comment text.
        This is a long comment text.
        This is a long comment text. This is a long comment text.
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
         
            $(".comment").shorten();
         
        });
    </script>
     You may want to pass the parameters to shoten()method and override the default ones.
    $(".comment").shorten({
        "showChars" : 200
    });
     
     
    $(".comment").shorten({
        "showChars" : 150,
        "moreText"  : "See More",
    });
     
    $(".comment").shorten({
        "showChars" : 50,
        "moreText"  : "See More",
        "lessText"  : "Less",
    });