如何实现点击容器外部或后代元素时隐藏容器?代码优化咨询
Hide Container on Click Outside or Its Descendants
Hey there! Let's tweak that jQuery code to match exactly what you need—hiding the container whenever you click either outside it or on any of its inner (descendant) elements. Here's how to make it work:
First, let's break down the original code's logic
The original code uses a condition that only hides the container if the clicked element is neither the container itself nor a descendant of the container. That's why it only triggers for clicks outside the container.
Modified Code
$(document).mouseup(function(e) { var container = $("YOUR CONTAINER SELECTOR"); // Hide the container if the clicked element isn't the container itself if (!container.is(e.target)) { container.hide(); } });
What changed?
- We removed the extra check
&& container.has(e.target).length === 0from the condition. That part was explicitly excluding clicks on descendant elements from triggering the hide action. By removing it, we now cover both scenarios you want:- Clicks on elements outside the container
- Clicks on elements inside the container (its descendants)
- The remaining condition
!container.is(e.target)simply checks if the clicked element isn't the container DOM element itself. If that's true—whether it's an outside element or a descendant—we hide the container.
Quick example
If your container is a modal with a close button inside it, clicking the button (a descendant) or clicking anywhere outside the modal will now hide the modal—exactly the behavior you're after.
内容的提问来源于stack exchange,提问作者lucke111222
相关产品推荐
相关产品推荐

