jQuery – 触发单击甚至后面的元素

我的问题是我有这个盒子又称容器。 在该容器内部,有用户可以单击的框。

为了在视觉上帮助用户,我制作了一个灰色褪色的覆盖盒,告诉他们可以在这里使用这些盒子。

但我的问题是点击事件位于覆盖框后面的框上。

那么有没有办法忽略元素的.click()并使用下一个目标?

在此处输入图像描述

您可以使用CSS pointer-events属性:

CSS属性pointer-events允许作者控制特定图形元素在什么情况下(如果有的话)可以成为鼠标事件的目标。

 #element { pointer-events: none; } 

或者您可以trigger click事件:

 $('#box').click(function(){ $('#target').trigger('click') }) 

避免CSS pointer-events ……

首先,确保所包含的框都具有类名box (或类似名称)。

其次,使用.addClass('inactive')使框不.addClass('inactive') ,(在样式表中使用相应的CSS指令来查看背景颜色和边框)。 要重新激活框,只需.removeClass('inactive')

第三,将盒子点击的处理委托给容器,如下所示:

 $('#container').on('click', '.box', function() { //common behaviour (pre) if($(this).hasClass("inactive")) { //inactive box behaviour } else { //active box behaviour } //common behaviour (post) }); 

您可以使用由Ivan Castellanos开发的立即调用函数表达式(IIFE)来检测鼠标指针的位置(x,y),并在您选择的元素上评估为真或假,实际上鼠标已经结束了元件。

通过利用Ivan的代码,我能够生成这个概念certificate,它将产生与pointer-events: none;相同的结果pointer-events: none; 但是在浏览器之间略微兼容。 它使用jQuery .offset()方法。 在jsFiddle中,有一个包含3个元素的页面,两个和一个

,它们叠加在按钮顶部,不透明度为50%。 在正常情况下,如果不调整z-index,您将无法单击这些元素。

jsFiddle示例

 //CSS Hitbox Solution 08-26-2015 //StackOverflow - https://stackoverflow.com/questions/32233084/show-an-element-without-hitbox-does-not-take-mouse-touch-input //Detect MouseOver https://stackoverflow.com/questions/1273566/how-do-i-check-if-the-mouse-is-over-an-element-in-jquery //Source: https://stackoverflow.com/questions/3942776/using-jquery-to-find-an-element-at-a-particular-position //https://css-tricks.com/snippets/jquery/get-xy-mouse-coordinates/ (function($) { $.mlp = { x: 0, y: 0 }; // Mouse Last Position function documentHandler() { var $current = this === document ? $(this) : $(this).contents(); $current.mousemove(function(e) { jQuery.mlp = { x: e.pageX, y: e.pageY }; }); $current.find("iframe").load(documentHandler); } $(documentHandler); $.fn.ismouseover = function(overThis) { var result = false; this.eq(0).each(function() { var $current = $(this).is("iframe") ? $(this).contents().find("body") : $(this); var offset = $current.offset(); result = offset.left <= $.mlp.x && offset.left + $current.outerWidth() > $.mlp.x && offset.top <= $.mlp.y && offset.top + $current.outerHeight() > $.mlp.y; }); return result; }; })(jQuery); $('.notification-box').on("click", function() { $("button").each(function(i) { var iteratedButton = $('button:eq(' + i + ')'); var buttonID = iteratedButton.attr("id"); if (iteratedButton.ismouseover()) { iteratedButton.toggleClass(buttonID); } }); }); 
 .notification-box { position: absolute; height: 100vw; width: 100vw; background-color: black; opacity: 0.5; /*pointer-events: none;*/ z-index: -10; overflow: visible; } button { position: absolute; top: absolute; width: 50px; z-index: -10; } button#no { margin-top: 25px; } .yes { color: red; font-weight: bold; } .no { color: blue; font-weight: bold; }