html文本超出隐藏,展开和收起。

主要是实现当文本的长度超出一定的长度时,文本剩余的部分省略,出现展开,点击展开,文本全部显示,点击收起,文本回复省略显示。

之前文本的超出多少行省略显示主要是用到以下的css样式来控制

 text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;/*行数*/
    line-clamp: 2;/*行数*/
    -webkit-box-orient: vertical;

现在来实现根据文本的长度,超出省略显示
效果如下:
在这里插入图片描述
在这里插入图片描述
主要用到的是封装好的插件函数,主要代码如下:

(function($) {
     
				/*
				 * 使用方法:1. $("you Dom ClassName or ID").overTexts({ texts:"you need overhide text...." });//这种的初始的,不带参数的,默认参数是 20字长 且显示展开和收起的
				 * texts: "测试文本...此处省略200字...测试文本",
				 * textLength: "20", //你需要定义超过多少字,就显示收起
				 * overText: "展开",  //你需要设置的默认名称,展开 显示
				 * openText: "收起",  //你需要设置的默认名称,收起 收缩
				 * ooType: "2" //展开和收缩的类型, 0 不显示展开和收缩,仅为省略号 || 1 显示展开,不显示收缩 ||2 显示展开和收缩 || 3显示省略号
				 * 
				 * */
				$.fn.overTexts = function(options) {
     
					var ooText,t1;
					var dft = {
     
						//初始化的参数配置
						texts: "展开和收缩的类型, 0 不显示展开和收缩,仅为省略号 || 1 显示展开,不显示收缩 ||2 显示展开和收缩",
						textLength: "40",
						overText: "展开",
						openText: "收起",
						ooType: "2" //展开和收缩的类型, 0 不显示展开和收缩,仅为省略号 || 1 显示展开,不显示收缩 ||2 显示展开和收缩 || 3显示省略号
					}
					var opt = $.extend(dft, options);
					ooText = opt.texts;			//临时装载 数据 用于填充到data-text内的
					if (options.ooType == '0') {
     
						$(this).html("
+opt.texts+">" + opt.texts + "
"
); } if (options.ooType == '1') { ooText = opt.texts; if (opt.texts.length > opt.textLength) { t1 = opt.texts.substring(0, opt.textLength) + ""+opt.overText+""; }else{ t1 = opt.texts; } $(this).html("
+ooText+">" + t1 + "
"
); } if (options.ooType == '2') { if (opt.texts.length > opt.textLength) { t1 = opt.texts.substring(0, opt.textLength) +'...'+ ""+opt.overText+""; }else{ t1 = opt.texts; } } if (options.ooType == '3') { if (opt.texts.length > opt.textLength) { t1 = opt.texts.substring(0, opt.textLength) + "..."; }else{ t1 = opt.texts; } } //无论何种结果,均执行此 $(this).html("
+ooText+">" + t1 + "
"
); //此处判断 就是 已经有展开或者收起了 if($(this).find("a").hasClass("moreoh")){ //事件委托,让他可以执行 $(".moreText").on("click","a.moreoh",function(){ //更多或者收起的点击事件 var moreoh = $(this).find("a.moreoh");//我是更多或者收起的dom if(moreoh.context.innerText== opt.overText){ //如果我此时是展开 if(opt.ooType==2){ t1 = opt.texts+ ""+opt.openText+""; moreoh.context.innerText = opt.openText; $(this).parents(".moreText").html(t1); }else{ t1=opt.texts; $(this).parents(".moreText").html(t1); } } if(moreoh.context.innerText== opt.openText){ //如果我此时是收起 t1 = opt.texts.substring(0, opt.textLength) + '...'+""+opt.overText+""; moreoh.context.innerText = opt.overText; $(this).parents(".moreText").html(t1); } }); } } })(jQuery);

使用如下:

 <div class="tip_txt">div>
$(".tip_txt").overTexts({
     
					texts: '在Web1.0时代,由于网速和终端能力的限制,大部分网站只能呈现简单的图文信息,并不能满足用户在界面上的需求,对界面技术的要求也不高。随着硬件的完善、高性能浏览器的出现和宽带的普及,技术可以在用户体验方面实现更多种可能,前端技术领域迸发出旺盛的生命力。',
					textLength: "50",
					overText: "展开",
					openText: "收起",
					ooType: "2" 					
				});

你可能感兴趣的:(html,html文本超出隐藏展开和收起)