DIV CSS 佈局教程網

無縫高度自適應滾動列表:jQuery 版與純 JavaScript 版實作對照
編輯:JQuery特效代碼     

要做一個類似 Twitter/新浪微博的資訊流,讓列表往上無縫捲動,是前端面試與日常開發都很常遇到的題目。這裡提供兩種寫法:一種用 jQuery,一種完全不用函式庫、只用原生 JavaScript,方便對照兩者的複雜度差異。

方案一:jQuery 版本

核心思路只有三步:把最後一項 li 的高度量出來、用 animate 把 ul 往上推一個項目加間距的距離、動畫結束後把最後一項搬到最前面並歸零 marginTop,視覺上就變成無縫循環。滑鼠移入時清掉計時器,移出時重新啟動,讓使用者能停下來閱讀。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
$(function () {
    var scrtime;
    $("#con").hover(function () {
        clearInterval(scrtime);              // 移入暫停
    }, function () {
        scrtime = setInterval(function () {  // 移出續跑
            var $ul = $("#con ul");
            var liHeight = $ul.find("li:last").height();
            $ul.animate({ marginTop: liHeight + 40 + "px" }, 1000, function () {
                $ul.find("li:last").prependTo($ul);
                $ul.find("li:first").hide();
                $ul.css({ marginTop: 0 });
                $ul.find("li:first").fadeIn(1000);
            });
        }, 3000);
    }).trigger("mouseleave");
});
</script>
<style type="text/css">
* { margin:0; padding:0; }
ul, li { list-style-type:none; }
body { font-size:13px; background-color:#999999; }
#con { width:700px; height:400px; margin:10px auto; position:relative;
       border:1px #666 solid; background-color:#FFFFFF; overflow:hidden; }
#con ul { position:absolute; margin:10px; top:0; left:0; padding:0; }
#con ul li { width:100%; border-bottom:1px #333333 dotted; padding:20px 0; overflow:hidden; }
#con ul li a { float:left; border:1px #333333 solid; padding:2px; }
#con ul li p { margin-left:68px; line-height:1.5; padding:10px; }
</style>
</head>
<body>
<div id="con">
  <ul>
    <li><a href="#"><img src="https://tp3.sinaimg.cn/1696357270/50/1282628065/1" /></a>
        <p>第一最好不相見,如此便可不相戀……</p></li>
    <!-- 其餘 li 結構相同 -->
  </ul>
</div>
</body>
</html>

方案二:原生 JavaScript 版本

不用函式庫時,手續明顯變多:要自己複製節點(cloneNode)、手寫 setInterval 做位移動畫、還得手動處理透明度(並且要照顧 IE 的 filter: alpha())。它分成 pos → anim → animH → animO → auto 五個步驟串成一個循環鏈。

<script type="text/javascript">
function H$(i) { return document.getElementById(i) }
function H$(c, p) { return p.getElementsByTagName(c) }

var slider = function () {
    function init(o) {
        this.id = o.id;
        this.at = o.auto ? o.auto : 3;   // 停留秒數
        this.o = 0;
        this.pos();
    }
    init.prototype = {
        pos: function () {
            clearInterval(this.__b);
            this.o = 0;
            var el = H$(this.id), li = H$('li', el), l = li.length;
            var _t = li[l - 1].offsetHeight;
            var cl = li[l - 1].cloneNode(true);   // 複製最後一項
            cl.style.opacity = 0;
            cl.style.filter = 'alpha(opacity=0)';
            el.insertBefore(cl, el.firstChild);   // 插到最前面
            el.style.top = -_t + 'px';
            this.anim();
        },
        anim: function () {
            var _this = this;
            this.__a = setInterval(function () { _this.animH() }, 20);
        },
        animH: function () {
            var _t = parseInt(H$(this.id).style.top);
            if (_t >= -1) {
                clearInterval(this.__a);
                H$(this.id).style.top = 0;
                var list = H$('li', H$(this.id));
                H$(this.id).removeChild(list[list.length - 1]);
                this.__c = setInterval(function () { _this.animO() }, 20);
            } else {
                var __t = Math.abs(_t) - Math.ceil(Math.abs(_t) * .07);
                H$(this.id).style.top = -__t + 'px';
            }
        },
        animO: function () {
            this.o += 2;
            if (this.o == 100) {
                clearInterval(this.__c);
                H$('li', H$(this.id))[0].style.opacity = 1;
                H$('li', H$(this.id))[0].style.filter = 'alpha(opacity=100)';
                this.auto();
            } else {
                H$('li', H$(this.id))[0].style.opacity = this.o / 100;
                H$('li', H$(this.id))[0].style.filter = 'alpha(opacity=' + this.o + ')';
            }
        },
        auto: function () {
            var _this = this;
            this.__b = setInterval(function () { _this.pos() }, this.at * 1000);
        }
    };
    return init;
}();
</script>

呼叫方式一行搞定:new slider({id:'slider'})。

兩種寫法的取捨

把兩份程式碼並排來看,結論其實很清楚:jQuery 版本用 hover+animate+prependTo 三個 API 就把事情做完了,程式碼短、可讀性高、跨瀏覽器問題也交給函式庫處理;原生版本雖然沒有外部依賴、體積更小,但要自己照顧邊界判斷與 IE 的 alpha 通道,維護成本明顯較高。若專案已經載入 jQuery,毫無疑問推薦前者。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved