2016-05-21 57 views
0

我知道这会让一个给定id的hoverOverhoverOut功能:jQuery的悬停了一个div

$(document).ready(function(){ 
    $("#link").hover(
     function(){ 
      $("#div").css({"display":"block"}); 
     }, 
     function(){ 
      $("#div").css({"display":"none"}); 
     } 
    ) 
}); 

但我想#div显示为无当鼠标移出主股利其中持有每个内容的ID为#main并淡出。所以我跑这个:

$(document).ready(function(){ 
    $("#link").hover(
     function(){ 
      $("#div").css({"display":"block"}); 
     }; 
    $("#main").hoverOut(
     function(){ 
      $("#div").fadeOut('slow').css({"display":"none"}); 
     }; 
}); 

但代码不显示#div作为none。请对jQuery仍然陌生,所以我需要有更好主意的人的帮助。这里是为了更好的解释HTML:

<div id="main"> 
    <a href="javascript:;" id="link">hover here</a> 
    <div id="div">this is the content</div> 
</div> 

回答

1

您可以使用mouseenter()mouseleave()

按照文档:

hover()方法结合两种mouseentermouseleave处理程序事件。

调用$(selector).hover(handlerIn, handlerOut)是简写: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);

$(document).ready(function() { 
 
    $("#link").mouseenter(function() { 
 
    $("#div").show(); // you can use show() method to show an element 
 
    }) 
 
    $('#main').mouseleave(function() { 
 
    $("#div").fadeOut('slow'); // fadeOut will hide the element, no need to hard-code css method 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="main"> 
 
    <a href="javascript:;" id="link">hover here</a> 
 
    <div id="div">this is the content</div> 
 
</div>

+1

谢谢。它的工作,但我更多的事情。我希望'mouseleave'和fadeOut('slow')'一起工作,但是它不能工作,请怎么运行? –

+0

@KANAYOAUSTINKANE:已更新 –

0

当你的光标进入主DIV显示它#div当光标离开主DIV它隐藏#div即从显示器阻止回到没有。

jQuery的,

$(document).ready(function(){ 
$("#main").mouseenter(function(){ 
    $("#div").css('display','block'); 
}); 
$("#main").mouseleave(function(){ 
    $("#div").css('display','none'); 
}); 
}); 
0

这是什么意思?

  1. 使用JS设置初始状态为display: none为内嵌式的
  2. 当鼠标进入#LINK,淡入#div
  3. 当鼠标离开#main,淡出#div

实施例:

$(document).ready(function() { 
    $("#div").css("display", "none"); 
    $("#link").on("mouseenter", function() { 
    $("#div").fadeIn('slow'); 
    }); 
    $("#main").on("mouseleave", function() { 
    $("#div").fadeOut('slow'); 
    }); 

}); 

http://codepen.io/anon/pen/oxrRJZ