开发者

Jquery toggleClass problem

please help me with my Jquery toggleClass menu.

It works properly, only if you stay on button more than 200ms, otherwise it fails.

This is the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript"></script>
<style>
.menu { width: 200px; padding: 5px; margin:10px 0;border:1px solid #FF0000;background: #FFFF00; color: #FF0000;display:block;}
.menu_over { width: 200px; padding: 5px; margin:10px 0; border:1px solid #000000;background: #FF0000; color: #ffffff;display:block;}
</style>
</head>
<body>
<script>
$(function() {
    $("#menu_left a开发者_运维问答.menu").hover(
        function() {
             $(this).toggleClass( "menu_over", 200 );
        }
    ),
        function() {
             $(this).toggleClass( "menu", 200 );
        }
});
</script>
<div id="menu_left">
    <a href="#" class="menu">AFRICA</a>
    <a href="#" class="menu">AMERICA</a>
    <a href="#" class="menu">ANTARCTICA</a>
    <a href="#" class="menu">ASIA</a>
    <a href="#" class="menu">AUSTRALIA</a>
    <a href="#" class="menu">EUROPE</a>
</div>
</body>
</html>


Nice solution Dutchie. A simple solution to this problem would be to stop the animation/fx queue. It'll mean you can continue to animate by toggling class.

var toggle = function() {
    $(this).stop(true, true).toggleClass( "menu_over", 200);
};

$("#menu_left a.menu").hover(toggle, toggle);

Fiddle: http://jsfiddle.net/NBdR5/10/


I'm not sure exactly why the fade is giving you those problems, but there are two problems I see with your code.

1) The main problem is that your .hover function is malformed.

The correct format is

$(item).hover(
   function(){}, //Actions on Mouseover
   function(){} //Actions on Mouseout
);

2) You're toggling one class on mouseover, and toggling a different class on mouseout. This is going to cause some odd results.

See my DEMO Without Fades for further illustration. Also, note my reduced/simplified CSS.

Your code should look similar to this

$("#menu_left a.menu").hover(function() {
    $(this).toggleClass( "menu_over");
},function() {
    $(this).toggleClass( "menu_over");
});

UPDATE

If you want to keep the fades, use animate() (DEMO)

$("#menu_left a.menu").hover(function() {
    $(this).stop().animate({
        'background-color': '#ff0000',
        'color' : '#ffffff',   
        'border-color' : '#000000'       
    }, 200);
},function() {
    $(this).stop().animate({
        'background-color': '#ffff00',
        'color' : '#ff0000',   
        'border-color' : '#ff0000'       
    }, 200);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜