這是一個不用任何套件的圖片展示效果:把同一張圖切成 3×3 的九塊,每塊用 <span> 包住並以絕對定位排在畫面上,再讓各塊以不同速度位移、縮放,看起來就像一整張圖在呼吸。以下為原始碼的關鍵節錄。
<style type="text/css">
body {
cursor: crosshair;
margin: 0; padding: 0;
position: absolute; overflow: hidden;
background: #222;
left: 0; top: 0;
width: 100%; height: 100%;
zIndex: -2;
}
</style>
<script type="text/javascript">
window.onerror = new Function("return true");
document.onselectstart = function () { return false; }
var NX = 3; // 水平切幾塊
var NY = 3; // 垂直切幾塊
var SP = 20; // 每塊間距
var DELAY = 96; // 動畫間隔毫秒
var object = new Array();
var nI = 0, run = false, xrun = 0, dR = 1;
var iW = 0, iH = 0, oH = 0, oW = 0;
</script>
function CObj(N, y, x) {
this.obj = document.createElement("span");
this.obj.onclick = new Function("object[" + N + "].GE1()");
this.obj.onmousedown = new Function("return false;");
this.obj.style.cursor = "pointer";
this.obj.style.position = "absolute";
this.img = document.createElement("img");
this.img.style.position = "absolute";
this.img.src = IMGSRC[N % nI].src;
this.obj.appendChild(this.img);
IMGBOX.appendChild(this.obj);
this.x = x; this.y = y; this.N = N;
this.W = 0; this.H = 0;
this.L = 0; this.T = 0;
}
用 createElement 組 DOM。整片拼貼圖不是寫死在 HTML 裡,而是用迴圈呼叫建構函式動態產生,這正是元件化思想的雛形。
用取餘數循環取圖。IMGSRC[N % nI].src 讓索引超過圖片數量時自動回到開頭,多張圖也能平均分配。
用 span 當裁剪容器。外層 span 設 overflow:hidden 當取景窗,內層 img 靠負的位移露出不同區塊——這是 CSS clip 之前的經典拼圖技法。
關掉不需要的瀏覽器行為。onselectstart 回傳 false 防止選字、onmousedown 回傳 false 防止拖曳,讓畫面保持乾淨。
同樣的效果用 CSS 就快了許多:把九塊做成 position:absolute 的 div,各自帶 background-image 與不同的 background-position,再用 @keyframes 加 animation-delay 錯開時間,完全不需要 JavaScript。若要更精細的控制,Web Animations API 的 element.animate() 也能取代手寫的 setTimeout 迴圈。
另外提醒:原始碼裡的 window.onerror = new Function("return true") 是把所有錯誤靜音,除錯時反而是障礙,正式環境也應該改用 window.addEventListener('error', ...) 把錯誤送到日誌,而不是藏起來。