[英]Why does my hover button dropdown not stay open when I mouse-over?
第一件事: http : //jsfiddle.net/9L81kfah/
我有一個 Bootstrap 下拉菜單,如果有人將鼠標懸停在 200 毫秒以上,它應該會打開並保持打開狀態,尤其是當他們將鼠標移到菜單內容上時,但它不會保持打開狀態。 我在這里做錯了什么?
這是下拉代碼:
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
和 jQuery:
jQuery('#dropdownMenu1').hover(function() {
jQuery(this).next('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function() {
jQuery(this).next('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
這是因為您的懸停處理程序位於按鈕元素上,一旦您將鼠標懸停在菜單元素上,“mouseout”處理程序就會觸發,因為您離開了按鈕。 相反,您的處理程序應該位於周圍的.dropdown
元素上。
$('.dropdown').hover(function () {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function () {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
現在,當您將鼠標懸停在按鈕上時,它將起作用,因為該按鈕是.dropdown
元素的子元素,並且懸停事件通過父元素向上冒泡。 當您將鼠標從按鈕移動到下拉菜單時,您仍然會懸停在.dropdown
,因為菜單也是.dropdown
的子.dropdown
。 只有當您完全離開父元素時,“mouseout”處理程序才會觸發。
鼠標離開按鈕后,您告訴下拉菜單淡出。 相反,您應該在鼠標移開整個下拉組后告訴它淡出。
jQuery('#dropdownMenu1').hover(function() {
jQuery(this).next('.dropdown-menu').stop(true, true).delay(200).fadeIn();
});
jQuery('.dropdown').on("mouseout", function() {
jQuery('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
您需要有一個計時器才能使其正常工作。 如果鼠標不在dropdown
則僅觸發淡出。 簡單地說,您可以結合使用mouseover
和mouseout
事件。
var timeout;
jQuery('.dropdown').on('mouseover', function () {
clearInterval(timeout);
jQuery('.dropdown-menu', this).stop(true, true).delay(200).fadeIn();
});
jQuery('.dropdown').on('mouseout', function () {
var thisView = this;
timeout = setTimeout(function () {
jQuery('.dropdown-menu', thisView).stop(true, true).delay(200).fadeOut();
}, 200);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.