I'm trying to make a navigation area and am trying to switch tabs with the active variable. This is just for the nav button, but later I'd like to make a rotator too b开发者_如何学运维y switching the variable.
Here is my code:
active = 1;
function hover() {
$(nav1).live('mouseenter', function() {
active = 2;
});
if ( active == 1) {
$(tab1).fadeIn('fast');
}
else if ( active != 1) {
$(tab1).fadeOut('slow');
}
if ( active == 2) {
$(tab2).fadeIn('fast');
}
else if ( active != 2) {
$(tab2).fadeOut('slow');
}
}
hover();
You should try
active = 1;
function showTab() {
if ( active == 1) {
$(tab1).fadeIn('fast');
}
else if ( active != 1) {
$(tab1).fadeOut('slow');
}
if ( active == 2) {
$(tab2).fadeIn('fast');
}
else if ( active != 2) {
$(tab2).fadeOut('slow');
}
}
$(nav1).live('hover', function() {
active = 1;
showTab();
});
$(nav2).live('hover', function() {
active = 2;
showTab();
});
Note that you need four vars tab1, tab2, nav1 and nav2 for this code.
Your tab selection "if ( active == 1) {..." is only called at the beginning. You'll need to call this switch loop again.
Because of your question if active equals 2 - obviously it does not. Do you mean
$(nav1).live('hover', function() {
active += 1;
});
This increases active every time you hover $(nav1). By the way: Do you mean $('nav1')?
If I understand what you're trying to do, then you might think about setting the 'active' variable to the actual menu item instead of a number. Also, you might be using jQuery .live() incorrectly and in addition, jQuery .delegate() is probably more useful in this case depending on your markup. (see jquery.com for info on these methods)
<html>
<head>
<script type="text/javascript">
// the active nav item:
var active;
// set up the hover events on each nav item only after the DOM is ready:
$(document).ready(function() {
$('.nav li').hover(function() {
// set the active nav item:
active = $(this);
// show the active nav item in the UI as test
alert(this.id);
});
});
</script>
</head>
<body>
<ul class="nav">
<li id="nav1">nav 1</li>
<li id="nav2">nav 1</li>
</ul>
</body>
</html>
精彩评论