JQuery CSS menu issue when menu item is active
I'm using a JQuery based css menu for my website. My problem however is if I click on one off the menu items. I want it to stay a cetain color, in my case the borrom half off the images.
I got my code from http://snook.ca/archives/javascript/jquery-bg-image-animations/ I used the second example. Heres the example page: http://snook.ca/technical/jquery-bg/
My code looks as follows
<script type="text/javascript">
$(function(){
$('#nav a')
.css( {backgroundPosition: "-20px 35px"} )
.mouseover(function(){
$(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:800})
})
.mouseout(function(){
$(this).stop().animate({backgroundPosition:"(40px 35px)"}, {duration:800, complete:function(){
$(this).css({backgroundPosition: "-20px 35px"})
}})
})
});
</script>
If y开发者_JAVA技巧ou hover over the menu the menu will change to a different color, that's the color I want the menu to stay when the menu is active and has been clicked on.
Hope someone could help me.
I tried as the answer said and still nothing
My modified code
<script type="text/javascript">
$(function(){
$('#nav a')
.css( {backgroundPosition: "-20px 35px"} )
.mouseover(function(){
$(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:800})
})
.mouseout(function(){
$(this).stop().animate({backgroundPosition:"(40px 35px)"}, {duration:800, complete:function(){
$(this).css({backgroundPosition: "-20px 35px"})
}})
})
$('#nav a').click(function() {
$('#nav a:not(.selected');
$('#nav a').removeClass('selected');
$(this).addClass('selected');
})
});
</script>
You should add a CSS class to the clicked links, not unlike this:
$('#nav a').click(function() {
$('#nav a').removeClass('selected');
$(this).addClass('selected');
})
Then, you can have a CSS declaration like:
.selected { background-position: -20px 35px; }
And finally, the mouseOver and mouseOut functions should be set to $('#nav a:not(.selected')
, if you don't want the CSS to be overwritten.
[EDIT] Here's the complete code:
$(function(){
$('#nav a:not(.selected)')
.css( {backgroundPosition: "-20px 35px"} )
.live('mouseover', function(){
$(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:800})
})
.live('mouseout', function(){
$(this).stop()
.animate({
backgroundPosition:"(40px 35px)"},
{duration:800, complete:function(){
$(this).css({backgroundPosition: "-20px 35px"});
}})
})
$('#nav a')
.live('click', function() {
$('#nav a').removeClass('selected');
$(this).addClass('selected');
});
});
With Alexander's code to add a selected class when items are selected you should be able to modify the mouse out listener like so:
.mouseout(function(){
// cache $(this) rather than executing it multiple times
var $this = $(this);
if (!$this.is('.selected')) {
$this.stop().animate(
{
backgroundPosition:"(40px 35px)"
},
{
duration:800,
complete:function()
{
$this.css({backgroundPosition: "-20px 35px"})
}
}
)
})
Hope it helps!
精彩评论