简体   繁体   English

jQuery将CSS设置为不显示后,悬停时显示的下拉菜单不起作用

[英]Dropdown menu show on hover doesn't work after jquery sets css to display none

I have a dropdown menu that has display: none and when hovering on parent it has display: block via CSS. 我有一个display: none的下拉菜单,将鼠标悬停在父菜单上时, display: block通过CSS display: block The dropdown menu links to anchors on the same page, so when I click I want the dropdown to disappear so I have on click 下拉菜单链接到同一页面上的锚点,因此当我单击时,我希望下拉列表消失,因此单击

$('.dropdown-menu').css("display", "none")

However, the jquery has now overridden the display: block that happens on hover. 但是,jQuery现在已覆盖display: block悬停时发生的display: block How can I keep the previous functionality while hiding the menu when clicking? 在单击时隐藏菜单时如何保持以前的功能?

JSFiddle of my code 我的代码中间

您是否尝试过jquery的.hover()

Add this into your javascript 将此添加到您的JavaScript

$(document).on('mouseover', '.dropdown', function(event) {
    $('.dropdown-content').css("display","block");
});

I've added another function to show the content again and edited your original a bit. 我添加了另一个功能以再次显示内容,并稍微编辑了原始内容。

https://jsfiddle.net/dc38u09p/6/ https://jsfiddle.net/dc38u09p/6/

$(document).on('click', 'a.hide-on-click', function(event) {
    $('.dropdown-content').hide();
});

$('.dropdown').on('mouseenter', function(){
    $('.dropdown-content').show();
});

Best then to use jQuery for hover and click actions. 然后最好使用jQuery进行悬停和单击操作。

Here it is quick solution: 这是快速的解决方案:

 // menu hover $(".dropdown").mouseover(function() { $('.dropdown-content').css("display", "block"); }) .mouseout(function() { $('.dropdown-content').css("display", "none"); }); //menu click $(".dropdown").click(function() { $('.dropdown-content').css("display", "none"); }); 
 /* Dropdown Button */ .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } /* The container <div> - needed to position the dropdown content */ .dropdown { position: relative; display: inline-block; } /* Dropdown Content (Hidden by Default) */ .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; } /* Links inside the dropdown */ .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } /* Change color of dropdown links on hover */ .dropdown-content a:hover { background-color: #f1f1f1 } .dropdown:hover .dropbtn { background-color: #3e8e41; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="dropdown"> <button class="dropbtn">Dropdown</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM