圖片依序顯示
by fu06h96z8
HTML
<div class="productanimate">
<img src="http://placehold.it/30x30">
<img src="http://placehold.it/30x30">
<img src="http://placehold.it/30x30">
<img src="http://placehold.it/30x30">
</div>
<button id="play" type="button">play</button>
<div id="info"></div>
CSS
.productanimate {
position: relative;
width : 150px;
height: 60px;
border:1px solid black;
overflow: hidden;
}
.productanimate img {
display : none;
position: absolute;
}
JavaScript
function func() {
// Step 1: 宣告變數
// x: 每張圖片移出距離
// duration: 每張圖片移出要耗費的秒數,愈後面的圖片因為移動距離比較大,要指定比較長的移出時間。視情況須自行調整。
// loopcount: 判斷所有圖片是否已經全部移出
// distance: 設定圖片定位點用。視情況自行調整。
var x = $('.productanimate img').first().outerWidth(true)
, duration
, loopcount = 0
, loopMax = $('.productanimate img').length - 1
, distance = x / 2
, debuginfo = ''
;
// Step 2: 設定圖片位置
// 使用 jQuery 針對每張圖片設定它的X軸位置
$('.productanimate img').show().each(function(i) {
$(this).css({
// 每張圖片間格為圖片寬度的一半
left: i * distance,
opacity: 0.5
});
});
// Step 3: 開始圖片移動
$('.productanimate img')
.first() // 先移動第一張圖片
.animate({ opacity: 1 }, 500).delay(1000).animate({ left: '-' + x + 'px' }, 200, function() {
// 匿名函式 --//START\\---------------------------------------
// 移動第一張圖片後要接著做的動作
x += distance;
loopcount = (loopcount > loopMax) ? 0 : loopcount; // 如果全部圖片都移出,則重新計數
duration = 500 + loopcount * 200; // 每張圖片移出時間,若要看起來等速移出,愈後面的圖片花的時間會比較長
if (loopcount >= loopMax){ // 檢查圖片是否全部移出,判斷是否停止圖片依序移出效果,並恢復按鈕功能
$('#play').attr('disabled', false);
}
++loopcount;
// debug --//START\\---------------------
debuginfo += '圖片: ' + loopcount + ', 移動距離: ' + x + ', 移動時間: ' + duration + '<br>\n'; //「\n」自行替換為 HTML 的 br 標籤(因 br 標籤在 syntaxhighlight 內無法正常顯示,故以 \n 代替
$('#info').html(debuginfo);
// debug --\\END//---------------------
$(this).next()
.animate({ opacity: 1 }, 500)
.animate({ left: '-' + x + 'px' }, duration, arguments.callee);
// 匿名函式 --\\END//--------------------------------------
});
};
$(window).load(function() {
$('#play').click(function(){
$(this).attr('disabled', true); // 按鈕...