.lay-on 類模擬 :hover。.recomm {
width: 600px; height: 170px; overflow: hidden;
border: 1px solid #666; background: #999; padding: 10px;
position: relative; margin: 0 auto;
}
.recomm ul {
width: 599px; height: 168px; overflow: hidden;
border: 1px solid #fff; border-left: none;
position: absolute; /* 修復 IE overflow 隱藏失效 */
}
.recomm li {
float: left; position: relative;
width: 70px; /* 收合狀寬度 = 圖片寬度 - 重疊 */
height: 100%; overflow: hidden;
margin-right: -179px; /* 負邊距實現重疊 */
white-space: nowrap; text-align: center;
}
.recomm li img {
display: block; width: 248px; height: 168px; border-left: 1px solid #fff;
}
.recomm li h5 {
position: absolute; bottom: 0; left: 0;
width: 239px; height: 20px; line-height: 20px;
background: url(../images/1_211621.png) no-repeat;
display: none; text-align: right; padding-right: 10px;
}
/* 關鍵:hover 展開 */
.recomm li:hover,
.recomm .lay-on { /* IE6 JS 添加的類 */
width: 249px; // 展開寬度
margin-right: 0; // 取消負邊距
}
.recomm li:hover h5,
.recomm .lay-on h5 {
display: block; // 顯示標題
}
<!--[if lte IE 6]>
<script>
var W3CDOM = (document.createElement && document.getElementsByTagName);
window.onload = function() {
if (!W3CDOM) return;
var all = document.getElementsByTagName('*');
for (var i=0; i<all.length; i++) {
if (all[i].className.indexOf('hovereffect') >= 0) {
all[i].onmouseover = function() {
this.className += ' lay-on';
};
all[i].onmouseout = function() {
this.className = this.className.replace(' lay-on', '');
};
}
}
};
</script>
<![endif]-->
<div class="recomm">
<ul>
<li class="hovereffect">
<a href="/" title="觀賞詳情">
<img src="/images/m01.jpg" alt="紅葉傳情" title="圖片標題" />
</a>
<h5>紅葉傳情 By <a href="/">代碼家園</a> 2010.09.23</h5>
</li>
<li class="hovereffect">...</li>
...
</ul>
</div>
| 技巧 | 原理 |
|---|---|
| 負邊距重疊 | margin-right: -179px 使 li 壓縮,僅露出左側窄條 |
| hover 展開 | width: 249px; margin-right: 0 恢復原寬,推開後續 li |
| overflow:hidden | 容器裁剪超出部分,形成「推擠」視覺 |
| IE6 不支援非 a 標籤 :hover | JS 掃描 .hovereffect 添加 .lay-on 類模擬 |
| absolute 修復 IE overflow | ul { position: absolute; } 觸發 hasLayout |
.recomm ul { display: flex; overflow-x: auto; scroll-snap-type: x mandatory; }
.recomm li { flex: 0 0 70px; transition: flex-basis 0.3s; scroll-snap-align: start; }
.recomm li:hover, .recomm li:focus-within { flex-basis: 249px; }
.recomm li h5 { opacity: 0; transition: opacity 0.2s; }
.recomm li:hover h5, .recomm li:focus-within h5 { opacity: 1; }
scroll-snap 提供原生吸附滑動體驗。:focus-within 支援鍵盤/觸控聚焦展開。「手風琴式圖片展開」是經典 CSS 布局技巧:負邊距重疊 + hover 恢復寬度 + overflow 裁剪。現代 Flexbox + Transition 可零 JS 實現更流暢效果,並原生支援觸控與無障礙。理解原理有助於在受限環境(舊專案、HTML 郵件)靈活應用。