在元素外部单击时隐藏元素 [英] Hide an element when clicking anywhere outside it

查看:113
本文介绍了在元素外部单击时隐藏元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在元素外部单击时,我试图将其隐藏.

I am trying to have an element be hidden when you click anywhere outside of it.

当您单击左上角的CART链接时,会出现一个下拉列表.我似乎要面对的问题有两个.

It is a drop down that appears when you click on the CART link in the top left. The problem I seem to be facing is two fold.

1)当您单击该按钮中的除CART以外的任何内容时,它都会显示出来,然后隐藏.cart-dropdown DIV.我猜这是因为我没有针对这段代码中的正确类:

1) When you click on anything in that button other then just CART, it's showing and then hiding the .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)当您单击.cart-dropdown DIV时,它也会关闭,这是我要避免的.同样,这必须与上述代码中的语法/逻辑错误有关.

2) The .cart-dropdown DIV also closes when you click within it, which is what I want to avoid. 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?

谢谢.

推荐答案

如果您更改检查类和元素的方式,它将起作用.使用下面的代码,请参见该小提琴作为一个工作示例:

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/

HTML:

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

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();
  }
});

您在正确的轨道上;您只需要像@Our_Benefactors所说的那样通过jQuery定位元素,然后更改检查元素类的方式即可.

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.

这篇关于在元素外部单击时隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆