化妝品、鞋子、3C 產品常需要「用手指轉一圈看產品」的效果。做法是把同一個物件從各個角度拍成一序列照片,然後依手指滑動的方向切換目前顯示的那張,視覺上就形成 3D 旋轉。
touchstart 記錄起始 X 座標。touchmove,當位移超過門檻(例如 10px)就切換幀:手指往左滑 → 幀號 +1,往右滑 → 幀號 -1。var step = 0; // 目前幀
var first = 0; // 上一次的 X 座標
var lth = document.querySelectorAll('#tobj img').length; // 總幀數
var frames = document.querySelectorAll('#tobj img');
function showFrame(n) {
frames[step].style.display = 'none';
step = n;
frames[step].style.display = 'block';
document.getElementById('outs').innerHTML = step;
}
window.addEventListener('touchstart', function (e) {
e.preventDefault();
first = e.touches[0].pageX;
}, { passive: false });
window.addEventListener('touchmove', function (e) {
e.preventDefault();
var x = e.pageX || e.touches[0].pageX;
if (Math.abs(x - first) > 10) { // 位移門檻,避免抖動
if (x < first) { // 往左滑:下一幀
step++;
if (step >= lth - 1) { step = 0; }
} else { // 往右滑:上一幀
step--;
if (step <= 0) { step = lth - 1; }
}
showFrame(step);
first = x; // 更新基準點
}
}, { passive: false });
window.addEventListener('touchend', function (e) {
e.preventDefault();
}, { passive: false });
if (Math.abs(x - first) > 10) {
frames[step].style.display = 'none';
if (x < first) { step++; if (step >= lth - 1) { step = 0; } }
else { step--; if (step <= 0) { step = lth - 1; } }
frames[step].style.display = 'block';
first = x;
}
原範例每次都用 querySelectorAll 重新取一次 NodeList,其實只要在最外層取一次存成變數就好,這在滑動這種高頻事件中對效能影響明顯。
反覆切 display 會觸發 layout。改成全部絕對定位重疊,只用 opacity 切換,會順很多:
#tobj { position: relative; }
#tobj img {
position: absolute; top: 0; left: 0;
opacity: 0;
transition: opacity .1s linear;
}
#tobj img.active { opacity: 1; }
frames.forEach(function (src) {
var img = new Image();
img.src = src;
});
否則第一次滑到某幀才去抓圖,會出現空白閃現。
var el = document.getElementById('tobj');
el.addEventListener('pointerdown', function (e) { first = e.clientX; });
el.addEventListener('pointermove', function (e) { /* 同上邏輯,讀 e.clientX */ });
Pointer Events 同時涵蓋滑鼠、觸控與手寫筆,不必再分開寫 touch 與 mouse 兩套。
24~36 幀通常就足夠流暢,每多一幀就多一份下載量。建議把圖片壓成 WebP,並依裝置解析度準備不同尺寸,避免手機下載桌機版的大圖。