这篇文章给大家分享的是有关JavaScript如何实现文字展开和收起效果的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
1:当文字超出目标值,则截取目标值,其他隐藏,同时显示“展开”二字和下拉箭头;
2:点击“展开”显示所有文字,同时改为“收起”和上拉箭头
3:如果文字本身就没有超过目标值,则显示所有文字即可
之前想过使用css设置超出多少行隐藏,或者给Li标签设置高度隐藏,但都无法满足以上第三条,所以想到了下边一种方法将就可以使用
1:初始遍历需要展开和收起的元素,超出目标值隐藏,然后把所有标签中的内容存起来(后边显示全部的时候会用到)
2:点击展开和收起的时候,根据当前的内容去存储的值中匹配,匹配到之后做相应的处理,展示出来
HTML
<ul class="outList">
<li>
<div>5-14号</div>
<ul class="innerList">
<li class="wordsContent">111111111111111111111111</li>
<li class="wordsContent">222222222222222222222222</li>
<li class="wordsContent">333333333333333333333333</li>
</ul>
</li>
<li>
<div>5-15号</div>
<ul class="innerList">
<li class="wordsContent">4444</li>
<li class="wordsContent">5555555555555555555555555</li>
<li class="wordsContent">6666666666666666666666666</li>
</ul>
</li>
</ul>
CSS
ul,li {
list-style: none;
}
.innerList>li {
margin-bottom: 0.2rem;
border-bottom: 0.01rem solid green;
box-sizing: border-box;
padding: 0.2rem 5% 0.7rem 3%;
position: relative;
margin-bottom: 0.3rem;
}
.open {
font-size: 0.22rem;
color: #12309E;
position: absolute;
right: 0.2rem;
bottom: 0.1rem;
font-weight: bold;
}
.close {
font-size: 0.22rem;
color: #12309E;
position: absolute;
right: 0.2rem;
bottom: 0.1rem;
font-weight: bold;
}
JS
//新闻的展开收起部分
var objList = $(".wordsContent"); //需要展开收起的li标签元素
var maxNum = 5; //目标值的长度
var arr = []; //需要展开收起的所有文字汇总
objList.delegate(".open", "click", function () {
openClose(true, this)
})
objList.delegate(".close", "click", function () {
openClose(false, this)
})
//初始化封装,初始化是为了1:存储原本的Li标签中的内容;2:超出目标值的文字隐藏
function init(objList, maxNum) {
objList.each(function (index, item) {
arr.push($(item_).text())
if ($(item).text().length > maxNum) {
$(item).html($(item).text().substr(0, maxNum) + "<span class='open'>展开<img src='./image/down^.png'/></span>")
}
})
}
init(objList, maxNum)
//展开和收起的封装
function openClose(boo, clickObj) {
var final = '';
arr.map(function (item, index) {
if (item.match($(clickObj).parents(".wordsContent").text().substring(0, $(clickObj).parents(".wordsContent").text().length - 2))) {
final = item
}
})
if (boo) {
$(clickObj).parents(".wordsContent").html(final + "<span class='close'>收起<img src='./image/up^.png'/></span>")
} else {
$(clickObj).parents(".wordsContent").html(final.substr(0, maxNum) + "<span class='open'>展开<img src='./image/down^.png'/></span>")
}
}
效果
感谢各位的阅读!关于“JavaScript如何实现文字展开和收起效果”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。