[英]jQuery adding background color on link when hover, background stay while mouse hovers sub-menu?
我試圖在主鏈接中添加背景色,該顏色顯示子菜單。 現在,僅顯示子菜單,一旦鼠標離開主鏈接,顏色就會恢復為原始背景色。
<nav>
<ul id="nav">
<li><a href="index.php">home</a>
</li>
<li><a href="intro.php">intro</a>
</li>
<li id="services"><a href="#">services</a>
<ul id="subMenu">
<li><span>one</span></li>
<li><span>two</span></li>
</ul>
</li>
<li><a href="contact.php">contacts</a>
</li>
</ul>
</nav>
<style>
#services {background:yellow;}
#subMenu {position:absolute;display:none;width:250px;}
#subMenu li {border:none;display:list-item!important;width:100%;background:#e13b30;}
#subMenu li span {color:#fff!important;line-height:50px;}
.bgRed {background-color:#e13b30;}
</style>
<script>
$(function(){
$('#nav #services').hover(
function () {
//show its submenu
$('#services', this).stop().addClass('bgRed'),
$('ul', this).stop().slideDown(100);
},
function () {
//hide its submenu
$('ul', this).stop().slideUp(10);
}
);
});
</script>
使用這樣的東西
$('#nav #services').hover(
function () {
//show its submenu
$(this).find("a").toggleClass('bgRed').stop();
$('ul', this).stop().slideDown(100);
},
function () {
//hide its submenu
$(this).find("a").toggleClass('bgRed').stop();
$('ul', this).stop().slideUp(10);
}
);
您的類定義也有錯誤
.bgRed{background-color,#e13b30;}
應該
.bgRed{background-color:#e13b30;}
注意:
將以下內容添加到您的腳本中
$('#submenu').hover(
function () {
//highlight parent
$(this).parent().addClass('bgRed');
},
function () {
//un - highlight parent
$(this).parent().removeClass('bgRed');
}
);
更新:在您從問題中刪除removeClass
怪異更新之后, 小提琴就很好了,我檢查了小提琴中的代碼,
在下面的代碼中
$('#services', this).stop().addClass('bgRed')
您將this
作為上下文傳遞。 因此,JQuery將在this
搜索具有id services
元素,該元素引用#services
元素本身。 因此它將無法正常工作。
也stop()
似乎是不必要的。
您也可以通過CSS實現此功能,並且不需要腳本。.請檢查此Fiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.