gpt4 book ai didi

css - 单击元素后关闭 css 悬停下拉菜单

转载 作者:行者123 更新时间:2023-11-28 08:40:22 24 4
gpt4 key购买 nike

我正在使用纯 css 下拉菜单。但是点击菜单项后,总是显示下拉菜单。当我将鼠标移出菜单时,它将被隐藏。单击菜单项后如何关闭纯 css 悬停下拉菜单?谢谢你的建议。这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Show Hide Dropdown Using CSS</title>
<style type="text/css">
ul{
padding: 0;
list-style: none;
background: #f2f2f2;
}
ul li{
display: inline-block;
position: relative;
line-height: 21px;
text-align: left;
}
ul li a{
display: block;
padding: 8px 25px;
color: #333;
text-decoration: none;
}
ul li a:hover{
color: #fff;
background: #939393;
}
ul li ul.dropdown{
min-width: 100%; /* Set width of the dropdown */
background: #f2f2f2;
display: none;
position: absolute;
z-index: 999;
left: 0;
}
ul li:hover ul.dropdown{
display: block; /* Display the dropdown */
}
ul li ul.dropdown li{
display: block;
}
</style>
</head>
<body>
<ul>
<li>
<a id="product" href="#">Products</a>
<ul class="dropdown">
<li><a onClick="document.getElementById('product').innerHTML = 'Laptop selected!'; return false;" href="#">Laptops</a></li>
<li><a href="#">Monitors</a></li>
<li><a href="#">Printers</a></li>
</ul>
</li>
</ul>

</body>
</html>

最佳答案

这是给你的 fiddle :https://jsfiddle.net/6a3xogfj/2/

我所做的是添加类来区分 .open.closed 下拉状态。

CSS

ul li ul.dropdown.closed { display: none; }
ul li ul.dropdown.open { display: block; }

剩下的是通过 jQuery 完成的。

JS

$('a#product').on('mouseover', function() {

$(this).siblings('ul.dropdown').removeClass('closed').addClass('open');
});

$('ul.dropdown a').on('click', function(e) {

e.preventDefault();

$(this).closest('ul.dropdown').removeClass('open').addClass('closed');
$('section').removeClass('active').filter( $(this).attr('href') ).addClass('active');
$('a#product').text( $(this).text() + " selected!");
});

当您将鼠标悬停在菜单项 #product 上时,下拉菜单将从 .closed 设置为 .open 并因此显示。一旦单击下拉项,这些类就会重置以关闭下拉列表。

关于css - 单击元素后关闭 css 悬停下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37322258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com