简体   繁体   English

在元素外部单击时隐藏元素

[英]Hide an element when clicking anywhere outside it

I am trying to have an element be hidden when you click anywhere outside of it. 当您单击元素外部的任何地方时,我都试图将其隐藏。

It is a drop down that appears when you click on the CART link in the top left. 当您单击左上角的CART链接时,会出现一个下拉列表。 The problem I seem to be facing is two fold. 我似乎要面对的问题有两个。

1) When you click on anything in that button other then just CART, it's showing and then hiding the .cart-dropdown DIV. 1)当您单击该按钮中除CART之外的任何内容时,它会显示出来,然后隐藏.cart-dropdown DIV。 I am guessing it's because I'm not targeting the correct classes in this piece of code: 我猜这是因为我没有针对这段代码中的正确类:

$(document).click (function (e) {
  if (e.target != $('.cart-dropdown')[0] && e.target != $('.cart-nav-item')[0] && e.target != $('.cart-full')[0]) {
    $('.cart-dropdown').hide();
  }
});

2) The .cart-dropdown DIV also closes when you click within it, which is what I want to avoid. 2) .cart-dropdown DIV在您单击它时也将关闭,这是我要避免的。 Again this must relate to an error in my syntax / logic in the above piece of code. 同样,这必须与以上代码中的语法/逻辑错误有关。

Can someone please point me in the correct direction? 有人可以指出正确的方向吗?

Thanks. 谢谢。

If you change the way you're checking the classes and elements, it will work. 如果您更改检查类和元素的方式,那么它将起作用。 See this fiddle for a working example, using the code below: 请使用以下代码查看此小提琴作为工作示例:

https://jsfiddle.net/freginold/kv44k1uu/ https://jsfiddle.net/freginold/kv44k1uu/

HTML: HTML:

<div>
  A div
</div>
<br>
<div id='cart' class='cart-dropdown'>
  Cart
</div>
<br>
<div>
 Another Div
</div>

CSS: CSS:

div {
  border: 1px solid blue;
  margin: 5px;
  display: inline-block;
}

JavaScript: JavaScript:

$(document).click (function (e) {
//alert($(e.target).hasClass("cart-dropdown"));
  if (!$(e.target).hasClass('cart-dropdown') && !$(e.target).hasClass('cart-nav-item') && !$(e.target).hasClass('cart-full')) {
    $('.cart-dropdown').hide();
  }
});

You were on the right track; 您走在正确的轨道上; you just had to target the element through jQuery like @Our_Benefactors said, and then change the way you checked the element's class. 您只需要像@Our_Benefactors一样通过jQuery定位元素,然后更改检查元素类的方式即可。

You need to change 你需要改变

e.target 

to

$(e.target) 

to treat it as a jquery object. 将其视为jquery对象。

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

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