使用Javascript隐藏CSS下拉菜单

时间:2016-10-25 01:52:05

标签: javascript jquery css

我有一个适用于CSS的下拉列表。我希望它在单击下拉列表中的项目时消失,但在单词后仍能正常运行。

这是我到目前为止所做的:



$("span").click(function(){
	$(this).parent().hide();
	$("#text").html("Try hovering over it again. Now it's broken, because the display attribute was set for the element.");
});

.dropDownContainer{
  display: inline-block;
}
.dropDown{
  display: none;
  padding-left: 6px;
  background-color: black;
  color:white; 
  position: absolute;
}

.dropDownContainer:hover .dropDown {
  display: block;
}
span{
  cursor:pointer;
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropDownContainer">
  hover over this
  <div class="dropDown">
    this is the dropdown<br><br>
  
    click <span>this</span> to close drop down.
    <br><br>
    It doesn't work.
  </div>
</div>
<div id="text">

</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您应该添加超时以在隐藏后立即删除显示。所以光标不会以自动重新打开的方式定位(在悬停时),所以很好。

$("span").off().click(function(){
    var dropdown = $(this).parent();
    dropdown.hide();
    setTimeout(function(){dropdown.removeAttr('style');}, 300);
    $("#text").html("Try hovering over it again. Now it's broken, because the display attribute was set for the element.");
});

答案 1 :(得分:0)

我已经更新了你的代码,看看这个小提琴:https://jsfiddle.net/dLcLoggx/1/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropDownContainer">
  <span class="trigger">hover over this</span>
  <div class="dropDown">
    this is the dropdown<br><br>

    click <span>this</span> to close drop down.
    <br><br>
    It doesn't work.
  </div>
</div>
<div id="text">

</div>

.dropDownContainer{
  display: inline-block;
}
.dropDown{
  display: none;
  padding-left: 6px;
  background-color: black;
  color:white; 
  position: absolute;
}


span{
  cursor:pointer;
  color: red;
}

$(".dropDown span").click(function(){
    $(this).parent().slideUp();
});

$("span.trigger").hover(function(){
    $('.dropDown').slideDown();
});

答案 2 :(得分:0)

您没有任何事件处理程序可以悬停并先打开它。如果你用CSS关闭或打开一些东西,你应该使用CSS打开或关闭它,JS / jQ也是如此,否则它们可能会发生冲突。

&#13;
&#13;
$(".dropDownHeader").on('mouseenter', function() {
  $(".dropDownContainer").show();
  $("kbd").on("click", function() {
    $('.dropDownContainer').hide();
  });
});
&#13;
.dropDownContainer {
  display: none;
  padding-left: 6px;
  background-color: black;
  color: white;
  position: absolute;
}
.dropDownHeader:hover .dropDown {
  display: block;
}
kbd {
  cursor: pointer;
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<header class="dropDownHeader">
  <h3>Hover over this</h3>
</header>
<div class="dropDownContainer">
  <p>This is the dropdown</p>

  <p>Click <kbd>this</kbd> to close drop down.</p>

  <p>It doesn't work.</p>
</div>

<article id="text">

</article>
&#13;
&#13;
&#13;