利用絕對定位圖層 clip 裁剪屬性配合 JavaScript 控制 left 與 clip 同步變化,製作可左右按鈕控制、滑鼠加速的橫向滾動展示區。
clip: rect(0 340 120 0) 僅顯示左側 340px 區域。slayer.style.left 移動內容、slayer.style.clip 同步調整可視窗口,產生滾動視差效果。<div id="slayer" style="position:absolute; top:120px; left:100px; clip:rect(0 340 120 0); height:120px; width:670px; background:#CCC;">
<!-- 內容如表格/圖片 -->
</div>
<script>
var layerW = 340; // 可視寬度 = clip right
var layerH = parseInt(slayer.style.height);
var layerL = parseInt(slayer.style.left);
var step = 0;
function movstar(a, time) {
if ((a < 0 && step > -parseInt(slayer.scrollWidth) + layerW) || (a > 0 && step < 0)) mov(a);
movx = setTimeout("movstar(" + a + "," + time + ")", time);
}
function movover() { clearTimeout(movx); }
function mov(a) {
step += a;
slayer.style.left = step + layerL;
slayer.style.clip = "rect(0 " + (layerW - step) + " " + layerH + " " + (-step) + ")";
}
</script>
在按鈕 (圖片或表格儲存格) 標籤添加:
onMouseDown="movover();movstar(3,2)" onMouseOut="movover()" onMouseOver="movstar(1,20)" onMouseUp="movover();movstar(1,20)"onMouseDown="movover();movstar(-3,2)" onMouseOut="movover()" onMouseOver="movstar(-1,20)" onMouseUp="movover();movstar(-1,20)"滑鼠懸停緩慢滾動,按住加速,離開停止。完整代碼可直接複製至 <body> 測試。