如何禁用特定div外的点击

问题描述 投票:1回答:3

这是示例代码。我想禁用搜索ID之外的点击。就像我们在弹出窗口中需要禁用外部点击一样

<body>
You can search <a href="google.com">here</a>
<div id="search">
Search
<input type="text" name=search><button>search</button> 
</div>
</body>
javascript jquery html
3个回答
2
投票

你可以使用:not() CSS选择器结合.preventDefault() JS函数:

$('*:not(#search)').click(function(e){
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.com">I don't work !</a>
<div id="search"></div>

3
投票

您可以创建一个具有固定位置的div,该div跨越整个屏幕并放置您希望能够在其中单击的内容,使该元素外部的所有点击实际上都在该“空”div上。

.disable-outside-clicks {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.enabled-clicks {
  width: 200px;
  margin: 0 auto;
}
<div>
  <button>This button will not work</button>
</div>

<div class="disable-outside-clicks">
  <div class="enabled-clicks">
    <button>This button will work</button>
  </div>
</div>

1
投票

也许css属性pointer-events是你要找的东西。

如果打开弹出窗口,则向body元素添加一个类。假设弹出窗口可见,你会将类.popup添加到body元素。那么你可以在css中这样做:

body.popup *:not(#search) {
    pointer-events: none;
}

这意味着,除了元素*之外,body元素中包含.popup类的每个元素(#search)都是不可点击的。

© www.soinside.com 2019 - 2024. All rights reserved.