我有一些 HTML 菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域之外单击时,我想隐藏这些元素。
jQuery可以做到这样的事情吗?
$("#menuscontainer").clickOutsideThisElement(function() { // Hide the menus });
注意:使用stopPropagation是应该避免的,因为它会破坏 DOM 中的正常事件流。有关更多信息,请参阅这篇 CSS 技巧文章。
stopPropagation
将单击事件附加到关闭窗口的文档正文。将单独的单击事件附加到容器,以停止传播到文档正文。
$(window).click(function() { //Hide the menus if visible }); $('#menucontainer').click(function(event){ event.stopPropagation(); });
如果您希望用户能够在元素内部单击并拖动,然后在元素外部释放鼠标,而不关闭元素:
... let lastMouseDownX = 0; let lastMouseDownY = 0; let lastMouseDownWasOutside = false; const mouseDownListener = (event: MouseEvent) => { lastMouseDownX = event.offsetX lastMouseDownY = event.offsetY lastMouseDownWasOutside = !$(event.target).closest(element).length } document.addEventListener('mousedown', mouseDownListener);
并在outsideClickListener:
outsideClickListener
const outsideClickListener = event => { const deltaX = event.offsetX - lastMouseDownX const deltaY = event.offsetY - lastMouseDownY const distSq = (deltaX * deltaX) + (deltaY * deltaY) const isDrag = distSq > 3 const isDragException = isDrag && !lastMouseDownWasOutside if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null element.style.display = 'none' removeClickListener() document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener() } }