這篇文章給大家分享的是有關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如何實現文字展開和收起效果”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。