本文介绍了如何允许点击通过div但仍然会对悬停做出反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 divA 部分重叠 divB 。如何允许点击 divA 来传递到 divB 但仍然有悬停 divA 时会触发code>?

Say I have divA that partially overlaps divB. How can I allow clicks on divA to pass through to divB but still have hover fired when hovering over divA?

我知道指针 - 事件:无; 这会使点击通过,但它也会阻止悬停。

I'm aware of pointer-events:none; and this makes the clicks pass through but it also prevents the hover.

我也试过以下,但是它不允许点击通过

I have also tried the below, but it did not allow clicks to fall through

$(document).on('click', '.feedback-helper', function(e){
        e.preventDefault();
})

想象一下div的关系,如:

Picture the relation of the divs like:

此处是它的原因(读作:让我们避免XY问题):

Here is the why of it (read as: "let's avoid an X Y problem"):

我正在研究 feedback.js

要查看问题:


  • 查看

  • 点击右下方的反馈按钮

  • 画一个方框在屏幕上突出显示一个部分

  • 点击停电按钮

  • 尝试在内部绘制
  • 第一个框你不能,因为点击被第一个框阻止
  • view the feedback.js demo
  • click the feedback button in the bottom right
  • draw a box on the screen to highlight a section
  • click the "black out" button
  • try to draw a box inside the first box you can't because the click is blocked by the first box

我需要允许绘图在突出显示的区域上的遮光框,但是如果我设置 pointer-events:none; 我将失去对这些元素的其他悬停功能。

I need to allow drawing a blackout box over a highlighted area but if I set pointer-events:none; I will lose other hover functionality I have on those elements.

欢迎所有解决方案

推荐答案

您可以获取点击事件重叠元素,用于启动底层元素的click事件。

You could get the click event for the overlaying element to initiate the click event for the underlying element.

Native JS示例:

Native JS Example:

document.getElementById('divA').addEventListener('click', function() {
  alert('Clicked A');
});
document.getElementById('divB').addEventListener('click', function() {
  var event = document.createEvent('HTMLEvents');
  event.initEvent('click', true, false);
  document.getElementById('divA').dispatchEvent(event);
});
div {
  cursor: pointer;  
  border: 1px solid black;
}
#divA {
  height: 300px;
  width: 300px;
  background: whitesmoke;
}
#divB {
  height: 30px;
  width: 30px;
  background: grey;
  position: absolute;
  left: 100px;
  top: 100px;
}
#divB:hover {
  background: green;  
}
<div id="divA"></div>
<div id="divB"></div>

jQuery示例:

$('#divA').on('click', function() {
  alert('Clicked A');
});
$('#divB').on('click', function() {
  $('#divA').trigger('click');
});
div {
  cursor: pointer;  
  border: 1px solid black;
}
#divA {
  height: 300px;
  width: 300px;
  background: whitesmoke;
}
#divB {
  height: 30px;
  width: 30px;
  background: grey;
  position: absolute;
  left: 100px;
  top: 100px;
}
#divB:hover {
  background: green;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divA"></div>
<div id="divB"></div>

这篇关于如何允许点击通过div但仍然会对悬停做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 09:37