這個效果在產品展示、圖片預覽上很常見:滑鼠移入時元素放大並改變層級,移出後復原。示範用 JavaScript 動態改寫樣式來達成。
#box {
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
background-color: green;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
這裡用了「絕對定位 + 負 margin」的經典居中手法:top/left 各 50% 把左上角推到中心,再用等於自身一半的負 margin 拉回來,元素就真正居中了。這個做法的好處是元素放大時中心點不會偏移。
window.onload = function () {
function zoom(id, x, y) {
// 參數:元素 id、橫向倍數、縱向倍數
var obj = document.getElementById("box");
var dW = obj.clientWidth; // 記錄原始寬度
var dH = obj.clientHeight; // 記錄原始高度
obj.onmouseover = function () {
this.style.width = dW * x + "px"; // 橫向放大
this.style.height = dH * y + "px"; // 縱向放大
this.style.backgroundColor = "#f00"; // 換色給回饋
this.style.zIndex = 1; // 提到最上層
};
obj.onmouseout = function () {
this.style.width = "";
this.style.height = "";
this.style.backgroundColor = "";
this.style.zIndex = "";
};
}
zoom("box", 1.5, 1.5); // 放大 1.5 倍
}
<div id="box"></div>
記得先存原始尺寸。如果把 dW、dH 的讀取寫在 onmouseover 裡面,第二次移入時就會拿放大後的尺寸再乘一次,元素越來越大直到爆掉。必須在綁定事件之前先存下來。
移出時設為空字串而非原值。this.style.width = "" 等於把行內樣式清除、交還給樣式表決定,這樣日後調整 CSS 尺寸時不用同步改 JS。
放大時記得處理層級。放大後的元素可能會被鄰居蓋住,設 z-index 是必要的;但要注意 z-index 只在 position 不為 static 時才生效,這裡已經是 absolute,所以沒問題。
如果今天重寫這個效果,用 CSS transition 會更流暢也更省事:#box { transition: all .3s ease; } #box:hover { transform: scale(1.5); }。用 transform 而非改 width/height,還能避免觸發重排(reflow),效能更好。