开发者

jQuery gets bugged on hover - why is that?

开发者 https://www.devze.com 2023-03-16 08:54 出处:网络
I have the following code: $(\".nav_button\").hover(function(){ m = $(this).children(\"ul\").css(\"display\");

I have the following code:

$(".nav_button").hover(function(){
m = $(this).children("ul").css("display");
if (m == "none"){
    $(this).children("ul").slideDown(300);
}
else{
    $(this)开发者_运维知识库.children("ul").slideUp(300);
}
});

And alot of times it gets bugged, sometimes it slides, stays, etc. Any idea why is that and how to correct it?


Use this one instead to get rid of checks and other non-related code

$(".nav_button").hover(function(){
    $(this).children("ul").slideToggle(300);
});

This will automatically slideUp or slideDown your UL according to the current state.

this is from official jQuery documentation:

slideToggle(); Display or hide the matched elements with a sliding motion.


I can not see any error in your code, maybe it could be re-written like this.

$(".nav_button").hover(function(){
  m = $(this).children("ul");
  if (m.css("display") == "none"){
   m.slideDown(300);
  }
  else{
   m.slideUp(300);
  }
});

In this way you are looking the element only one time in the DOM


Use like this :

$(".nav_button").hover(function(){
     m = $("ul").css("display");
     alert(m);
     if (m == "none") {
         $("ul").slideToggle(300);        
     }
     else {
         $("ul").slideToggle(300);
     }
});

See the Demo: http://jsfiddle.net/rathoreahsan/JAA9q/4/

or You can use like this:

$(".nav_button").hover(function(){
    m = $("#toggleUL").css("display");
    alert(m);
    if (m == "none") {
        $("#toggleUL").slideToggle(300);        
    }
    else{
        $("#toggleUL").slideToggle(300);
    }
});

See the Demo: http://jsfiddle.net/rathoreahsan/JAA9q/7/


unless there is only one child 'ul', the m = $(this).children("ul").css("display") would return an array, so in the next statement if (m == 'none') it could break. You probably want a .each there to tread each ul

0

精彩评论

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

关注公众号