我有我的HTML代码:
<div id="bot-bar">
<nav class="main-nav" id="main">
<a id="home" href="/">Home</a>
<a id="events" href="events.php">Events</a>
<a id="news" href="news.php">News</a>
<a id="ranks" href="ranks.php">Ranks</a>
<a id="media" href="media.php">Media</a>
</nav>
</div>
当我将鼠标悬停在<a>
标记上时,它应该更改bot-bar
div的颜色。我怎么能做到这一点?
答案 0 :(得分:4)
var botBar = $('#bot-bar');
botBar.find("a").hover(function(){
botBar.css({backgroundColor: "red"}); // mouseenter event
}, function(){
botBar.css({backgroundColor: "green"}); // mouseleave event
});
或稍短(性能较差但显示某些可能性):
$('#bot-bar a').hover(function( ev ){
$(this).closest("div").css({background: ev.type=="mouseenter"?"red":"green"});
});
获取当前悬停的元素背景:
var botBar = $('#bot-bar');
var botBarBg = botBar.css("background-color");
botBar.find("a").hover(function(){
var bg = $(this).css("background-color");
botBar.css({backgroundColor: bg}); // mouseenter event
}, function(){
botBar.css({backgroundColor: botBarBg}); // mouseleave event
});
<强> jsBin demo 强>