如何禁用特定div外的点击

时间:2017-05-24 07:50:45

标签: javascript jquery html

以下是示例代码。我想禁用搜索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>

3 个答案:

答案 0 :(得分: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 :(得分:2)

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

&#13;
&#13;
$('*:not(#search)').click(function(e){
  e.preventDefault();
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

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

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

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

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