<ul>
<li class="menu">
<div class="title"><span>電腦數碼類產品</span></div>
<ul class="content">
<li class="optn">
<a href="#">筆記本</a>
<ul class="tip">
<li><a href="#">筆記本1</a></li>...
</ul>
</li>
<li class="optn"><a href="#">移動硬盤</a><ul class="tip">...</ul></li>
...
</ul>
</li>
</ul>
.menu { width:190px; border:1px solid red; background:#fffdd2; }
.optn { width:190px; line-height:28px; border-top:1px dashed red; }
.tip { width:190px; border:2px solid red; position:absolute; background:#fff; display:none; }
.optnFocus { background:#fff; font-weight:bold; }
$(function(){
var $optn = $('.optn'), $tip = $('.tip');
function pos($el) {
return { top: $el.offset().top - $el.height(), left: $el.offset().left + $el.width() };
}
$optn.on('mouseenter', function(){
var $this = $(this).addClass('optnFocus');
var p = pos($this);
$tip.hide(); // 先隱藏所有
$this.find('.tip').css(p).show();
}).on('mouseleave', function(){
$(this).removeClass('optnFocus').find('.tip').hide();
});
// 子選單也要綁定,防止移入子選單時消失
$tip.on('mouseenter', function(){
$(this).show().prev('.optn').addClass('optnFocus');
}).on('mouseleave', function(){
$(this).hide().prev('.optn').removeClass('optnFocus');
});
});
mouseenter/mouseleave 而非 mouseover/mouseout,避免子元素觸發冒泡導致閃爍。left = 父選單右邊、top = 父選單頂部 - 父選單高度(依設計調整)。.optn { position: relative; }
.tip { position: absolute; left: 100%; top: 0; display: none; }
.optn:hover > .tip { display: block; }
無需 JS、效能最佳、行動裝置需搭配 touchstart 處理。
aria-haspopup="true"、aria-expanded 屬性。