點擊或懸停主選單,平滑展開子選單;移開自動收合。適合導航欄、下拉面板等場景。
<div class="UpLayer">
<dl>
<dt><a href="javascript:void(0)">腳本之家</a></dt>
<dd>
<a href="https://www.demo.com/js/">特效</a>
<a href="https://www.demo.com/Tutorials/">教程</a>
<a href="https://www.demo.com/zy/">資源</a>
<a href="https://www.demo.com/mb/">模板</a>
<a href="https://www.demo.com/news/">資訊</a>
</dd>
</dl>
</div>
.UpLayer { margin: 100px; }
.UpLayer dl dt {
width: 50px; position: absolute; z-index: 3;
padding: 0 5px; line-height: 20px;
}
.UpLayer02 { /* 點擊/懸停時 dt 樣式 */
border: 1px solid #ccc; border-bottom: none;
background: #f1f1f1; margin: -1px 0 0 -1px;
}
.UpLayer dl dd {
width: 80px; position: absolute; z-index: 2;
border: 1px solid #ccc; padding: 5px;
line-height: 20px; background: #f1f1f1;
display: none; margin: 19px 0 0 -1px;
}
.UpLayer dl dd a { display: block; border-bottom: 1px dashed #ccc; }
$(document).ready(function() {
var objStr = '.UpLayer';
$(objStr).each(function(i) {
var $this = $(this);
var $dd = $(objStr + ' dd').eq(i);
var $dt = $(objStr + ' dt').eq(i);
// 點擊展開
$this.click(function() {
$dd.show();
$dt.addClass('UpLayer02');
});
// 懸停控制
$this.hover(function() {}, function() {
$dd.hide();
$dt.removeClass('UpLayer02');
});
});
});
.UpLayer 綁定獨立事件,避免多實例干擾。eq(i) 精準匹配當前實例的 dt/dd。click 展開,hover 的 mouseleave 收合,體驗更豐富。dt (3) 覆蓋 dd (2),視覺上形成整體邊框。focus/blur 邏輯。touchstart/touchend 並處理穿透問題。