1. 程式人生 > 程式設計 >基於jQuery實現列表迴圈滾動小技巧(超簡單)

基於jQuery實現列表迴圈滾動小技巧(超簡單)

看到一個很好的思路,記錄一下

之前使用做滾動效果,在這兩篇文章裡有寫:文一、文二,分別使用了scrollLeft()與scrollTop()、scroll()來實現

後來看到一個demo,覺得思路很妙,想著可以用來做列表內容項的滾動,效果大概是這樣的:
在這裡插入圖片描述

思路是這樣的:
只要能夠不停地把第一個item移動到末尾,其餘的自會往上填補空缺,填補的過程用動畫放慢些,就能有不斷滾動的視覺效果了(陣列刪了第一個元素,再在末尾加上這個元素,等於把第一個元素移動到末尾;元素總量沒有改變,但位置全發生了改變)

程式碼:

// 要填充的資料
 var data = {
     infoItem : [
         "<strong>第1行:</strong>安之安之安之安之安之安之安之安之安之安之安","<strong>第2行:</strong>陽光彩虹小白馬陽光彩虹小白馬陽光彩虹小白馬","<strong>第3行:</strong>天地之悠悠天地之悠悠天地之悠悠天地之悠悠天"
     ]
 }
 // 將資料動態填充到頁面種
 var infoList = []
 for (let i = 0; 
i < data.infoItem.length; i++){ let infoStr = `<div class="item">${data.infoItem[i]}</div>` infoList.push(infoStr); } $(".info-wrapper").html(infoList.join("")) // 設定計時器,每隔2秒執行一次(變換一次) var timer = null; timer = setInterval(function () { // 將第一行item移到最後一行,其他的往上挪填補空缺位 var infoItemTmp = infoList.shift(); $(".info-wrapper").append(infoItemTmp ); $(".item:first").remove(); infoList.push(infoItemTmp) },2000)

html和樣式部分:

<div class="container">
        <div class="wrapper">
            <div class="info">
                <div class="info-wrapper"></div>
            </div>
        </div>
    </div>
.constainer {
    width: 900px;
    height: 400px;
    border: 2px solid #eee;
    display: flex;
    justify-content: center;
    align-items: center;
}

.wrapper {
    width: 500px;
    height: 300px;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-content: center;
}

.info {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-content: center;
}

.info-wrapper {
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.item {
    border: 2px solid #ccc;
    border-left: 4px solid orange;
    height: 80px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    border-radius: 8px;
    margin-top: 20px;
}

目前效果是這樣的:

在這裡插入圖片描述

再加上滑動效果的動畫:

.item:first-child {
    animation: move 2s lineawww.cppcns.comr;
}
@keyframes move {
    100% {
        margin-top: -80px;
    }
}

不斷滑動,到達可以加入新item的位置時,觸發新item的加入:

// 設定計時器,每隔2秒執行一次(變換一次)--與animation動畫時設定時間一致
var timer = null;
timer = setInterval(function () {
    if ($('.info').scrollTop() + $('.info').heightwww.cppcns.com() >= $('.info-wrapper').height()) {
        // 將第一行item移到最後一行,其他的往上挪填補空缺位
        var infoItemTmp = infoList.shift();
        $(".info-wrapper").append(infoItemTmp);
        $(".item:first").remove();
        infoList.push(infhttp://www.cppcns.comoItemTmp)
    }
},2000)

就可以得到開頭的效果了

到此這篇關於基於jQuery實現列表迴圈滾動小技巧(超簡單)的文章就介紹到這了,更多相關jQuery列表迴圈滾動內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!