我有这个 html 结构:
<div class="dropdownedit">
<div class="dropbtn">textxyz</div>
<div class="dropdown-content" style="display: none;">
<div href="#" class="ocond" id="text1">text1</div>
<div href="#" class="ocond" id="text2">text2</div>
<div href="#" class="ocond" id="text3">text3</div>
<div href="#" class="ocond" id="text4">text4</div>
</div></div>
和这个 jquery 事件来处理下拉视图/隐藏事件:
$(document).on('click',".dropdownedit", function (e) {
$(this).children('.dropdown-content').css("display", "block");
});
$(document).on('mouseover',".dropdown-content", function (e) {
$(this).css("display", "block");
});
$(document).on('mouseout',".dropdown-content", function (e) {
$(this).css("display", "none");
});
此外,我有一个“ocond”类的点击事件,当在下拉菜单中单击一个选项时,它应该关闭下拉内容类:
$(this).parents('.dropdown-content').css("display", "none");
但点击后它不会关闭它保持可见。我猜它与以下冲突:
$(document).on('click',".dropdownedit", function (e) {
$(this).children('.dropdown-content').css("display", "block");
});
由于 dropdownedit 是“ocond”类 div 的父级,并且当有人点击“ocond”类时也会被触发。
当单击子事件时,我尝试添加以防止父事件:
$(".dropdownedit .ocond").click(function(e) {
e.stopPropagation();
});
但没有成功。我怎样才能解决这个冲突?
你是对的,命令相互冲突。如果您将click
事件降一级,该事件旨在让菜单保持打开状态并添加一个类来覆盖hover
显示/隐藏功能,那么您将获得所需的结果而不会发生冲突。
将.click()
事件附加到.dropbtn
并.nextAll()
用于查找.dropdown-content
将避免当前冲突。
注意,我使用了.nextAll()
它来查找与特定选择器匹配的所有兄弟姐妹,我遵循了这个,.first()
以便代码只影响它的第一个实例。这意味着它不太可能干扰其他代码。
我还强烈建议使用.closest()
(它将在上游立即找到第一次出现的选择器)而不是.parents()
匹配任何。
$(".dropbtn").click( function() {
$(this).nextAll(".dropdown-content").first().show();
});
$(".dropdownedit").mouseleave( function() {
$(this).find(".dropdown-content").hide();
});
$(".ocond").click( function() {
$(this).closest('.dropdown-content').hide();
});
.dropdown-content {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdownedit">
<div class="dropbtn">textxyz</div>
<div class="dropdown-content">
<div href="#" class="ocond" id="text1">text1</div>
<div href="#" class="ocond" id="text2">text2</div>
<div href="#" class="ocond" id="text3">text3</div>
<div href="#" class="ocond" id="text4">text4</div>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句