這支效果模仿新浪微博側欄的圖文列表:圖片與文字成組上下間歇滾動,進場淡入、離場淡出,並在主流瀏覽器(IE6/IE7/IE8 以上、Firefox、Google Chrome)都能正常運作。
先讓容器固定顯示 4 個項目,多餘的 li 先移除並存入陣列中。接著用計時器觸發動畫:每次把下一個項目以「高度 0、透明度 0」插入列表頂端,同時讓最底部的項目淡出後移除,於是畫面看起來就像整串內容持續向上滾動。因為每個 li 視為一個整體(圖片+標題+時間),進場與離場的時機就是它進入與離開容器可視範圍的時刻。
把檔案下載解壓後,圖片資料夾名稱無須變更(已與程式碼中的路徑對應)。建立 HTML 檔時建議選用「UTF-8(含簽名)」編碼,存檔類型選「所有檔案」,並把 HTML 與解壓後的圖片資料夾放在同一層。
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
(function($){
$.fn.simpleSpy = function(limit, interval){
limit = limit || 4; // 容器固定顯示 4 個項目
interval = interval || 4000; // 每輪動畫間隔 4 秒
return this.each(function(){
var $list = $(this), items = [], currentItem = limit, total = 0,
height = $list.find('> li:first').height();
// 先把所有 li 的內容存進陣列
$list.find('> li').each(function(){
items.push('<li>' + $(this).html() + '</li>');
});
total = items.length;
// 固定外層高度,避免項目消失時容器塌陷
$list.wrap('<div class="spyWrapper" />').parent().css({height: height * limit});
// 畫面上只留 limit 個
$list.find('> li').filter(':gt(' + (limit - 1) + ')').remove();
function spy(){
// 新項目從頂端插入,初始高度與透明度皆為 0
var $insert = $(items[currentItem])
.css({height:0, opacity:0, display:'none'})
.prependTo($list);
// 最底部的項目先淡出
$list.find('> li:last').animate({opacity:0}, 1000, function(){
// 新項目撐開高度後再淡入
$insert.animate({height:height}, 1000).animate({opacity:1}, 1000);
$(this).remove();
});
currentItem++;
if(currentItem >= total){ currentItem = 0; } // 輪完一圈回到開頭
setTimeout(spy, interval);
}
spy(); // 啟動
});
};
})(jQuery);
</script>
<script type="text/javascript">
$(document).ready(function(){
$('ul.spy').simpleSpy();
});
</script>
HTML 本體就是一個 ul.spy,每個 li 內含圖片、h5 標題與 p.info 資訊:
<div id="sidebar">
<ul class="spy">
<li>
<a href="..." title="View round"><img width="70" height="70" src="images/1.png" /></a>
<h5><a href="...">round</a></h5>
<p class="info">Nov 29th 2008 by neue</p>
</li>
<!-- 其餘 li 結構相同 -->
</ul>
</div>
CSS 的關鍵是給 li 固定高度並隱藏溢出的內容,讓每次滾動的位移剛好等於一個項目高度:
*{margin:0;padding:0;list-style-type:none;}
a,img{border:0;}
body{font:12px/180% Arial, Helvetica, sans-serif, "新細明體";}
#sidebar{color:#AFB0B1;background:#0D171A;float:left;margin:0 0 24px;padding:15px 10px 10px;width:300px;}
#sidebar li{height:90px;overflow:hidden;}
#sidebar li h5{color:#A5A9AB;margin-bottom:0.5em;}
#sidebar li h5 a{color:#fff;text-decoration:none;}
#sidebar li img{float:left;border:solid 3px #fff;margin-right:8px;display:inline;}
#sidebar li .info{color:#B1B1B1;}
#sidebar .spyWrapper{height:100%;overflow:hidden;position:relative;}
整個插件化寫法讓它可以重複套用到多個列表上,只要給 ul 加上 spy class 並呼叫 simpleSpy() 即可,limit 與 interval 兩個參數也能依版面調整。