javascript 单击外部/悬停在外部时关闭的下拉菜单

dluptydi  于 2023-01-04  发布在  Java
关注(0)|答案(3)|浏览(156)

所以我现在正在做一个下拉列表菜单,你可能会怀疑......我是个新手。我希望这样做,当我打开下拉菜单时,当我悬停或点击它的外部时,下拉菜单应该再次隐藏。如何才能做到这一点呢?我已经尝试了一些技巧在这里Stackoverflow,但没有一个是为我工作可悲的。
正如你所看到的,这是一个onclick="toggle_visibility"为我的下拉菜单称为(ID)"droppy"它有一个默认的display:none;,所以当我点击<a>标签,它打开"droppy "/下拉菜单。但如果它应该再次关闭时,无论是悬停在外面或只是点击外面。两种解决方案都适合我=)如果有人知道,请帮助。谢谢!

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'block')
        e.style.display = 'none';
    else
         e.style.display = 'block';
    }
#nav #droppy{
	position:relative;
	left:90px;
	top: 17px;
	width: 225px;
	height: 150px;
	display:none;
	font-size: 25px;
	background-color: #304749;
	border-bottom: 1.6px solid black;
}
<div id="nav">
  <div id="fall">
    <a href="#" ="javascript:void(0)" onclick="toggle_visibility('droppy');">Menu</a>
  </div>
  <div id="droppy">
    <a href="airplanes">Våra Flygplan</a>
  </div>
</div>
bis0qfac

bis0qfac1#

看这段代码,我已经使用悬停事件

/*
$( "#menu" ).hover(
  function() {
    $( "#droppy" ).show();
  }, function() {
    $( "#droppy" ).hide();
  }
);
*/
$("#menu").on("click",function(){
  $( "#droppy" ).show();
});

$( "#droppy" ).hover(
  function() {
    
  }, function() {
    $( "#droppy" ).hide();
  }
);
#nav #droppy{
	position:relative;
	left:90px;
	top: 17px;
	width: 225px;
	height: 150px;
	display:none;
	font-size: 25px;
	background-color: #304749;
	border-bottom: 1.6px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">
  <div id="fall">
    <a href="#" ="javascript:void(0)" id="menu">Menu</a>
  </div>
  <div id="droppy">
    <a href="airplanes">Våra Flygplan</a>
  </div>
</div>
5ktev3wc

5ktev3wc2#

见下面的代码.增加了点击事件打开菜单和鼠标事件隐藏.

$('#fall a').mouseout(function() {
  $('#droppy').hide();
}).click(function(){
$('#droppy').show();
});
#nav #droppy{
	position:relative;
	left:90px;
	top: 17px;
	width: 225px;
	height: 150px;
	display:none;
	font-size: 25px;
	background-color: #304749;
	border-bottom: 1.6px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">
  <div id="fall">
    <a href="#" ="javascript:void(0)">Menu</a>
  </div>
  <div id="droppy">
    <a href="airplanes">Våra Flygplan</a>
  </div>
</div>
im9ewurl

im9ewurl3#

<div id="parent_div">
  <div id="drop_down">
    <ul>
      <li>your_info</li>
    </ul>
  </div>
</div>

<script type="application/javascript">
  //close on hover outside #drop_down effect
  $(document).on("mouseleave", "#drop_down", function() { 
    $("#drop_down").css("display", "none");
  });

  //close on click outside #drop_down effect
  $(document).on("click mouseup", function(e) { 
    if($(e.target).closest("#drop_down").length === 0) {
      $("#drop_down").css("display", "none");
    }
  });
</script>

相关问题