要做的新聞列表效果是這樣:一則新聞滾入視圖後停留幾秒,接著向上滾出並淡出,同時下一則新聞滾入。本文用 jQuery 實作這個功能,若有不足之處歡迎指教。
因為一次只顯示一則新聞,容器的 wysokości 就設定為單則的高度(這裡用 200px),超出的部分以 overflow: hidden 隱藏;每則標題則用絕對定位,方便以 top 做動畫。
<style>
#news-feed {
padding: 0;
margin: 0 0 0 10px;
position: relative;
height: 200px;
width: 17em;
overflow: hidden;
}
.headline {
position: absolute;
height: 200px;
top: 210px;
overflow: hidden;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#news-feed').each(function () {
var $container = $(this);
$container.empty();
$.get('feed.xml', function (data) {
// 讀取 XML,組出每則新聞的 HTML 並附加到容器
$('rss item', data).each(function () {
var $link = $('<a></a>')
.attr('href', $('link', this).text())
.text($('title', this).text());
var $headline = $('<h4></h4>').append($link);
var pubDate = new Date($('pubDate', this).text());
var pubMonth = pubDate.getMonth() + 1;
var pubDay = pubDate.getDate();
var pubYear = pubDate.getFullYear();
var $publication = $('<div></div>')
.addClass('publication-date')
.text(pubMonth + '/' + pubDay + '/' + pubYear);
var $summary = $('<div></div>')
.addClass('summary')
.html($('description', this).text());
$('<div></div>')
.addClass('headline')
.append($headline, $publication)
.appendTo($container);
});
var currentHeadline = 0, oldHeadline = 0;
var hiddenPosition = $container.height() + 10;
$('div.headline').eq(currentHeadline).css('top', 0); // 第一則先置於可見位置
var headlineCount = $('div.headline').length;
var pause;
var headlineRotate = function () {
currentHeadline = (oldHeadline + 1) % headlineCount;
// 舊標題向上滾出,回到下方等待位置
$('div.headline').eq(oldHeadline).animate(
{ top: -hiddenPosition }, 'slow',
function () { $(this).css('top', hiddenPosition); }
);
// 新標題滾入
$('div.headline').eq(currentHeadline).animate(
{ top: 0 }, 'slow',
function () { pause = setTimeout(headlineRotate, 4000); }
);
oldHeadline = currentHeadline;
};
pause = setTimeout(headlineRotate, 4000);
// 滑鼠移入暫停輪播,移出後恢復
$container.hover(
function () { clearTimeout(pause); },
function () { pause = setTimeout(headlineRotate, 3000); }
);
});
});
});
</script>
<body>
<form id="form1" runat="server">
<div id="sidebar">
<h3>Recent News</h3>
<div id="news-feed">
<a href="###">News Releases</a>
</div>
</div>
</form>
</body>
樣式部分:一次只顯示一則,所以容器高度等同單則高度,超出隱藏。
資料來源:這裡用 feed.xml。jQuery 讀取 XML 檔很簡單,取出資料稍作組裝,就得到要顯示的 HTML 片段並附加到容器中。
狀態維護:需要兩個變數——一個記錄目前可見的標題索引,一個記錄剛滾出視圖的標題索引。同時要把目前那則設為 top: 0,且位置屬性不能是 static,否則 absolute 定位無效。
輪播邏輯:舊標題動畫到負值(視圖上方之外)後,在回呼中把 top 重設到容器下方等待;新標題同時動畫到 0,動畫結束後再排下一次的 setTimeout,形成循環。用取餘運算 % headlineCount 讓索引自動回到開頭。
互動細節:用 hover 在滑鼠移入時 clearTimeout 暫停輪播,移出後重新計時,避免使用者正在閱讀時內容被捲走。
jQuery 還有許多外掛可以更簡化這些操作,值得繼續研究。想入門的話,個人推薦 Jonathan Chaffer 的 jQuery 基礎教程,很適合初學者。