`

Dynamically shortened Text with “Show More” link using jQuery

阅读更多

文章源自:http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/

Dynamically shortened Text with “Show More” link using jQuery

Update: The plugin is now on GitHub: https://github.com/viralpatel/jquery.shorten

Facebook user updates has a great functionality. If the comment text is larger than few characters, the extra words are hide and a show more link is presented to user. This way you can keep long text out of the view to user and stop the cluttering of page. Also interested users can click on more link and see the full content.

Here is a simple tutorial to achieve this using jQuery / Javascript.

The HTML

Below is the sample text. Each text is wrapped in a DIV tag. Note that we have added a class “more” in each div. This class will decide if a text needs to be shortened and show more link showed 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 “.morecontent span” is 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 tags with class “more” and split the text in two. First half is showed to user and second is made hidden with a link “more..”.

You can change the behaviour by changing following js variables.

  • showChar: Total characters to show to user. If the content is more then showChar, it will be split into two halves and first one will be showed to user.
  • ellipsestext: The text displayed before “more” link. Default is “…”
  • moretext: The text shown in more link. Default is “more”. You can change to “>>”
  • lesstext: 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 enhanced. HTML tags are now parsed properly within text to preserve its uniformity while shorting the text. Please check latest plugin code on GitHub. https://github.com/viralpatel/jquery.shorten


jQuery Plugin

Code

/*
 * 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 in 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 shorten any DIV content. In below example we are shortening DIV with class “comment”.

<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 shorten() 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",
});

 

 

  • 大小: 1.7 KB
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    毕业设计-客服系统-整站商业源码.zip

    毕业设计-客服系统-整站商业源码.zip

    软考初级信息处理技术员(上机)下午试题模拟17及答案.docx

    软考初级程序员相关文档

    毕业设计-砍价宝7.2.0开源-整站商业源码.zip

    毕业设计-砍价宝7.2.0开源-整站商业源码.zip

    毕业设计-广告机-整站商业源码.zip

    毕业设计-广告机-整站商业源码.zip

    多类别动物目标检测数据集.zip

    数据集介绍:多类别动物目标检测数据集 一、基础信息 数据集名称:多类别动物目标检测数据集 图片数量: - 训练集:6,860张图片 - 验证集:1,960张图片 - 测试集:980张图片 总计:9,800张含动态场景的动物图像 分类类别: Alpaca(羊驼)、Camel(骆驼)、Fox(狐狸)、Lion(狮子)、Mouse(鼠类)、Ostrich(鸵鸟)、Pig(猪)、Rabbit(兔子)、Rhinoceros(犀牛)、Shark(鲨鱼)、Sheep(绵羊)、Snake(蛇)、Whale(鲸鱼) 标注格式: YOLO格式标注,包含目标检测所需的归一化坐标及类别索引,适用于YOLOv5/v7/v8等系列模型训练。 数据特性: 覆盖航拍、地面视角等多种拍摄角度,包含动态行为捕捉及群体/单体目标场景。 二、适用场景 野生动物监测系统: 支持构建无人机/红外相机AI识别系统,用于自然保护区动物种群追踪与生态研究。 智慧农业管理: 适用于畜牧养殖场动物行为分析、数量统计及健康监测等自动化管理场景。 生物多样性研究: 为陆地/海洋生物分布研究提供标注数据支撑,助力濒危物种保护项目。 教育科研应用: 可作为计算机视觉课程实践素材,支持目标检测、迁移学习等AI教学实验。 三、数据集优势 跨物种覆盖全面: 包含13类陆生/水生动物,涵盖家畜、野生动物及濒危物种,支持复杂场景下的模型泛化训练。 动态场景丰富: 捕捉动物运动、群体互动等真实行为模式,提升模型对非静态目标的检测鲁棒性。 标注体系规范: 严格遵循YOLO标注标准,提供精确的边界框定位,支持即插即用的模型训练流程。 多场景适配性: 数据来源涵盖航拍影像、地面监控等多维度视角,适用于农业、生态保护、科研等跨领域应用。 类别平衡优化: 通过分层抽样保证各类别数据分布合理性,避免长尾效应影响模型性能。

    三菱FX5U与英威腾GD变频器Modbus通讯程序及应用详解 工业自动化 三菱FX5U与英威腾GD变频器Modbus通讯程序(含注释与参数设置)

    内容概要:本文详细介绍了如何利用三菱FX5U PLC与三台英威腾GD变频器进行Modbus通讯的具体实现方法。主要内容涵盖硬件连接、参数设置、程序逻辑以及常见问题解决。文中提供了详细的接线图、参数配置步骤、关键代码片段,并分享了一些实用的经验技巧。此外,还特别强调了通讯稳定性的重要性和一些容易忽视的技术细节。 适合人群:自动化控制系统工程师、工业通信技术人员、PLC编程人员。 使用场景及目标:适用于需要将三菱FX5U PLC与多台英威腾GD变频器集成的应用场景,如工厂自动化生产线、机械设备控制等。主要目的是实现对变频器的远程频率设定、启停控制及状态监测,确保系统的高效稳定运行。 阅读建议:读者可以先了解整个项目的背景和技术选型原因,然后重点研读具体的硬件连接方式、参数配置要点和程序逻辑设计思路。对于初学者来说,建议跟随文中的步骤逐步实践,同时注意作者提到的各种注意事项和避坑指南。

    ATB2012-75011-T00-射频组件-中文数据手册.pdf

    ATB2012-75011-T00-射频组件-中文数据手册

    陆生动物多场景目标检测数据集.zip

    数据集介绍:陆生动物多场景目标检测数据集 一、基础信息 数据集名称:陆生动物多场景目标检测数据集 数据规模: - 训练集:9,134张图片 - 验证集:1,529张图片 - 测试集:1,519张图片 分类类别: - 家畜类:Cattle(牛)、Horse(马)、Sheep(羊) - 宠物类:Cat(猫)、Dog(狗) - 野生动物类:Bear(熊)、Deer(鹿)、Elephant(大象)、Monkey(猴子) - 禽类:Chicken(鸡) 标注格式: YOLO格式标注,包含目标边界框坐标和10类动物标签,支持多目标检测场景 数据特性: 涵盖俯拍视角、户外自然场景、牧场环境等多角度拍摄数据 二、适用场景 农业智能化管理: 支持开发牲畜数量统计、行为分析系统,适用于现代化牧场管理 野生动物保护监测: 可用于构建自然保护区动物识别系统,支持生物多样性研究 智能安防系统: 训练农场入侵检测模型,识别熊等危险野生动物 宠物智能硬件: 为宠物智能项圈等设备提供多动物识别训练数据 教育科研应用: 适用于动物行为学研究和计算机视觉教学实验 三、数据集优势 物种覆盖全面: 包含10类高价值陆生动物,覆盖畜牧、宠物、野生动物三大场景需求 标注质量优异: YOLO格式标注严格遵循标准规范,支持YOLOv5/v7/v8等主流检测框架直接训练 场景多样性突出: 包含航拍视角、近距离特写、群体活动等多种拍摄角度和场景 大规模训练保障: 超12,000张标注图片满足深度神经网络训练需求 现实应用适配性: 特别包含动物遮挡、群体聚集等现实场景样本,提升模型部署效果

    工业自动化中信捷XD5 PLC与英威腾GD变频器通讯程序及触摸屏设置详解 变频器

    内容概要:本文详细介绍了信捷XD5 PLC与三台英威腾GD系列变频器的通讯程序实现及其与昆仑通态7022Ni触摸屏的接线和设置方法。主要内容涵盖硬件设备简介、通讯程序的具体实现步骤(如初始化设置、轮询机制、频率设定、启停控制、实际频率读取)、触摸屏的接线方式和设置说明,以及程序调试与优化。文中提供了详细的注释,确保程序的可靠性与稳定性。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是那些需要掌握PLC与变频器通讯编程的人群。 使用场景及目标:适用于需要实现PLC与多台变频器通讯并集成触摸屏控制的实际工程项目。目标是帮助工程师理解和实施可靠的通讯程序,提高系统的稳定性和效率。 其他说明:本文不仅提供了具体的编程和接线指导,还强调了调试和优化的重要性,为实际应用提供了全面的支持。

    毕业设计-聚合客服V25.3.0+PC端插件V6.2.0 原版-整站商业源码.zip

    毕业设计-聚合客服V25.3.0+PC端插件V6.2.0 原版-整站商业源码.zip

    2021年下半年网络规划设计师论文.pdf

    软考初级程序员相关文档

    基于蒙特卡洛模拟的电动汽车充电负荷预测.pdf

    基于蒙特卡洛模拟的电动汽车充电负荷预测.pdf

    中国书画艺术作品印章真伪检测算法研究.pdf

    中国书画艺术作品印章真伪检测算法研究.pdf

    基于CDM积分状态反馈与PSO优化KT模型的无人艇航向控制MATLAB程序研究 KT模型

    内容概要:本文详细介绍了两种用于船舶和无人艇(USV)航向控制的技术方法及其MATLAB实现。第一种方法是基于CDM积分状态反馈控制,它通过不断获取和比较系统实际状态与期望状态之间的差值,动态调整控制策略,确保航向的精确控制。第二种方法是基于粒子群优化(PSO)算法对KT模型进行优化,进而获得更优的PID控制参数,提高航向控制的精度。文中提供了具体的MATLAB代码示例,展示了这两种方法的具体实现步骤和技术细节。 适合人群:从事船舶工程、自动化控制以及海洋科技领域的研究人员和工程师。 使用场景及目标:适用于需要深入了解和掌握先进船舶航向控制技术和MATLAB编程实现的研究人员和从业者。目标是提升船舶航行的安全性和效率,同时为相关领域的技术创新提供理论支持和技术指导。 其他说明:文章不仅涵盖了理论知识,还包括了实用的编程技巧,有助于读者将所学应用于实际项目中。

    毕业设计-挪车V1.8.5商业多开版 原版-整站商业源码.zip

    毕业设计-挪车V1.8.5商业多开版 原版-整站商业源码.zip

    毕业设计-码科货运快狗搬家物流V1.0.11 小程序前端+后端-整站商业源码.zip

    毕业设计-码科货运快狗搬家物流V1.0.11 小程序前端+后端-整站商业源码.zip

    易优CMS响应式法律咨询律师事务网站模板-EyouCMS商业服务类企业网站模板

    易优CMS响应式法律咨询律师事务网站模板,EyouCMS商业服务类企业网站模板。适用于财务、管理、法律、政府类企业网站开发使用。 模板自带eyoucms内核,无需再下载eyou系统,原创设计、手工书写DIV+CSS,完美兼容IE7+、Firefox、Chrome、360浏览器等;主流浏览器;结构容易优化;多终端均可正常预览。

    毕业设计-导航V1.0-集网址-整站商业源码.zip

    毕业设计-导航V1.0-集网址-整站商业源码.zip

    BC817-40W-通用NPN晶体管-中文数据手册.pdf

    BC817-40W-通用NPN晶体管-中文数据手册

Global site tag (gtag.js) - Google Analytics