DIV CSS 佈局教程網

jQuery 圖片翻閱實作:上一張、下一張一次搞定
編輯:關於JavaScript     

做圖片展示區時,「上一張/下一張」幾乎是標配功能。本文以 jQuery 為基礎,示範兩種由簡到繁的寫法,並提醒一個容易被忽略的重點:邊界判斷。

核心思路:用陣列管理圖片清單

假設 images 目錄下放著 1.jpg 到 5.jpg,檔名剛好有規律可循,那麼只需要維護一個「目前索引」,就能推算出該載入哪張圖。

var array = [1, 2, 3, 4, 5];
var count = 0;

array 存放圖片編號,count 是游標位置。往後翻就 count++,往回翻就 count--,再用 $('img').attr('src', ...) 把來源換掉即可。

版本一:表格排版的最小可用版

<head>
<title>圖片翻閱</title>
<script src="Jquery1.7.js" type="text/javascript"></script>
<style type="text/css">
img { width: 200px; height: 200px; }
</style>
<script type="text/javascript">
$(function () {
    var array = [1, 2, 3, 4, 5];
    var count = 0;

    $('#Button1').click(function () {
        if (count > 0) {          // 已經是第一張就不能再退
            count--;
            $('img').attr('src', 'images/' + array[count] + '.jpg');
        }
    });

    $('#Button2').click(function () {
        if (count < 4) {          // 還沒到最後一張才能前進
            count++;
            $('img').attr('src', 'images/' + array[count] + '.jpg');
        }
    });
});
</script>
</head>
<body>
<table>
<tr>
<td><input id="Button1" type="button" value="<" /></td>
<td><img src="images/1.jpg" /></td>
<td><input id="Button2" type="button" value=">" /></td>
</tr>
</table>
</body>

這裡的 4 其實就是 array.length - 1。實務上建議直接用 length 計算,之後增減圖片就不用改程式。

版本二:加入置中排版,並示範 toggle 寫法

如果希望圖片固定在畫面正中央,可以用絕對定位加上負 margin 的經典手法:

#mydiv {
    position: absolute;
    width: 500px;
    height: 400px;
    top: 50%;
    left: 50%;
    margin-top: -200px;
    margin-left: -290px;
}
img { width: 480px; height: 380px; }

切換邏輯有兩條路。第一種是 toggle() 一次掛多個函式,每按一次就往下走一格,走完再回到頭:

$('#btn1').toggle(
    function () { $('img').attr('src', 'images/1.jpg'); },
    function () { $('img').attr('src', 'images/2.jpg'); },
    function () { $('img').attr('src', 'images/3.jpg'); },
    function () { $('img').attr('src', 'images/4.jpg'); },
    function () { $('img').attr('src', 'images/5.jpg'); }
);

這種寫法缺點很明顯:圖片數量必須寫死,而且 jQuery 1.9 之後已移除 .toggle(fn, fn) 這個多函式簽名,因此更推薦第二種「索引 + 邊界判斷」的做法:

var array = [1, 2, 3, 4, 5, 6];
var count = 0;

// 後退
$('#btn1').click(function () {
    if (count > 0) {
        count--;
        $('img').attr('src', 'images/' + array[count] + '.jpg');
    }
});

// 前進
$('#btn2').click(function () {
    if (count < 5) {
        count++;
        $('img').attr('src', 'images/' + array[count] + '.jpg');
    }
});

完整結構如下:

<body>
<div id="mydiv">
<table>
<tr>
<td><input id="btn1" type="button" value="<" /></td>
<td><img src="images/1.jpg" /></td>
<td><input id="btn2" type="button" value=">" /></td>
</tr>
</table>
</div>
</body>

可以再加強的地方

若圖片很多,建議改用「索引直接對應陣列」而非 if 判斷,並在到頭尾時把按鈕 disable 掉,使用者會更清楚目前狀態。想做成自動輪播,只要把這段換成 setInterval 週期呼叫前進函式,並讓 count 到底後歸零即可。

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