三個絕對定位的 <div> 重疊排列,點擊任一層將其置頂(z-index: 100),其餘置底(z-index: 0),模擬視窗切換交互。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>多層重疊點擊切換</title>
<style>
.layer {
position: absolute;
width: 150px; height: 150px;
border: 2px solid #333;
cursor: pointer;
transition: box-shadow 0.2s, transform 0.2s;
}
.layer:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.3); transform: translate(-2px, -2px); }
#a1 { left: 50px; top: 50px; background: #ddeeff; z-index: 1; }
#a2 { left: 100px; top: 80px; background: #eeffdd; z-index: 2; }
#a3 { left: 150px; top: 110px; background: #ffddee; z-index: 3; }
</style>
</head>
<body>
<div id="a1" class="layer" onclick="changeLayer(1)">Layer 1</div>
<div id="a2" class="layer" onclick="changeLayer(2)">Layer 2</div>
<div id="a3" class="layer" onclick="changeLayer(3)">Layer 3</div>
<script>
function $(id) { return document.getElementById(id); }
function changeLayer(n) {
for (var i = 1; i <= 3; i++) {
$('a' + i).style.zIndex = (i === n) ? 100 : 0;
}
}
</script>
</body>
</html>
z-index 僅在定位元素(relative/absolute/fixed/sticky)生效。z-index 設為最大值,其餘歸零,實現「置頂」視覺。transition 讓層級變更有平滑過渡(陰影/位移)。function LayerSwitcher(containerSelector, layerSelector) {
var container = document.querySelector(containerSelector);
var layers = container.querySelectorAll(layerSelector);
var maxZ = layers.length + 10;
layers.forEach(function(layer, idx) {
layer.style.zIndex = idx + 1;
layer.addEventListener('click', function() {
layers.forEach(function(l) { l.style.zIndex = 0; });
this.style.zIndex = maxZ;
});
});
}
// 使用
LayerSwitcher('#stackContainer', '.stack-layer');
此封裝支援任意數量層級,自動計算最大 z-index,解耦 HTML 結構。