本文示範如何以 ASP.NET 的 AjaxPro 搭配原生圖片切換效果,做一個資料驅動的圖片輪播:圖片清單來自資料庫,切換時套用轉場動畫,全程不刷新頁面。
using System.Data;
using System.Data.SqlClient;
namespace AjaxImage
{
public class AjaxMethod
{
public static string ConnectionString =
System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();
public static DataSet GetDataSet(string sql) {
SqlDataAdapter sda = new SqlDataAdapter(sql, ConnectionString);
DataSet ds = new DataSet();
sda.Fill(ds);
return ds;
}
[AjaxPro.AjaxMethod]
public static DataSet GetPhotoList(int iCategoryID) {
string sql = "select id, photo_path from Photo where photo_category_id="
+ iCategoryID;
return GetDataSet(sql);
}
[AjaxPro.AjaxMethod]
public static DataSet GetPhotoInfo(int id) {
string sql = string.Format(
"select photo_title, photo_description from Photo where id = {0}", id);
return GetDataSet(sql);
}
}
}
兩個公開方法都掛上 [AjaxPro.AjaxMethod],AjaxPro 便會自動產生對應的用戶端代理,前端可以直接以 AjaxImage.AjaxMethod.GetPhotoList(2) 的形式呼叫。
<div id="Layer1" style="position:absolute; left:104px; top:28px; width:501px; height:345px">
<img name="slideShow" src="images/space.gif" width="500" height="300"
style="filter:revealTrans(duration=2,transition=23)" />
</div>
<div id="Layer2" style="position:absolute; left:490px; top:380px">
<img id="btnPlay" src="images/play_bw.gif" onclick="slideshow_automatic()" />
<img id="btnPause" src="images/pause_bw.gif" onclick="pauseSlideShow()" />
<img id="btnPrev" src="images/prev_bw.gif" onclick="previous_image()" />
<img id="btnNext" src="images/next_bw.gif" onclick="next_image()" />
</div>
四個控制鈕分別負責自動播放、暫停、上一張、下一張。圖片元素上的 filter:revealTrans 是 IE 專屬的轉場效果屬性,也是這個特效的視覺來源。
先宣告全域狀態:
var timeDelay; // 計時器 var timeInterval = 4000; // 自動輪播間隔(毫秒) var image; // 圖片路徑陣列 var num; // 目前顯示的索引 var dt; // 圖片資訊資料表
接著是預載入函式。它以同步方式取得圖片清單,把路徑存進陣列,並用 Image 物件提前把圖片抓進瀏覽器快取,避免切換時出現白屏:
function PreloadImage(iCategoryID) {
var ds = AjaxImage.AjaxMethod.GetPhotoList(iCategoryID).value;
if (!ds) return;
if (ds.Tables[0].Rows.length > 0) {
dt = ds.Tables[0];
image = new Array();
for (var i = 0; i < dt.Rows.length; i++) {
image[i] = "Photos/" + dt.Rows[i].photo_path;
}
// 預快取:把 src 指向圖片即可讓瀏覽器提前下載
var imagePreload = new Array();
for (var i = 0; i < image.length; i++) {
imagePreload[i] = new Image();
imagePreload[i].src = image[i];
}
num = -1;
next_image();
} else {
alert("該目錄下沒有圖片!");
}
}
轉場效果由 revealTrans 的 Transition 屬性決定,數值 0 到 23 對應 24 種切換樣式:
function image_effects() {
document.slideShow.filters.revealTrans.Transition = Math.random() * 23;
document.slideShow.filters.revealTrans.apply();
document.slideShow.filters.revealTrans.play();
}
換圖函式用取餘運算達成環狀循環,走到尾端就回到開頭:
function next_image() {
num++;
num %= image.length;
image_effects();
document.slideShow.src = image[num];
}
function previous_image() {
num += image.length - 1;
num %= image.length;
image_effects();
document.slideShow.src = image[num];
}
function slideshow_automatic() {
num++;
num %= image.length;
image_effects();
document.slideShow.src = image[num];
timeDelay = setTimeout("slideshow_automatic()", timeInterval);
}
function pauseSlideShow() {
clearTimeout(timeDelay);
}
在頁面的 onload 事件中啟動預載入:
<body onload="PreloadImage('2')">
在 Web.config 註冊 AjaxPro 的 handler,並設定連線字串:
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro" />
</httpHandlers>
</system.web>
<configuration>
<appSettings>
<add key="ConnectionString"
value="server=127.0.0.1;database=test;uid=sa;pwd=你的密碼" />
</appSettings>
</configuration>
資料表結構:
CREATE TABLE [Photo] (
[id] [int] IDENTITY(1,1) NOT NULL,
[photo_title] [varchar](128) NULL,
[photo_description] [text] NULL,
[photo_category_id] [int] NULL
)
這個範例有清楚的教學價值,但若要在今天上線,有幾處必須調整:
GetPhotoList 用字串串接組 SQL,務必改用 SqlParameter 參數化查詢;GetPhotoInfo 也一樣。connectionStrings 區段,並為資料庫帳號開最小權限,別用 sa。PreloadImage 使用同步的 AjaxPro 呼叫,在慢網路下會讓整頁卡住直到回應到來;改為非同步並在回呼中啟動輪播即可。eval,請改成直接傳函式:setTimeout(slideshow_automatic, timeInterval)。:hover 取代,省下額外的圖檔與事件屬性。把上述幾點改過之後,這個輪播的核心邏輯(索引環狀遞增、預快取、計時器控制)依然適用,只是把 IE 專屬的轉場換成標準 CSS 動畫、把資料存取換成參數化查詢而已。