javascript - 避免在绝对定位的子元素上移动鼠标

标签 javascript css dom mousemove

我试图了解绝对元素上的 mousemove 事件。

我做了一个Codepen来展示我想要的东西。

我需要在 #main 元素上捕获 mousemove,但不在它的任何绝对定位的子元素上。

HTML:

<div id="main">
  <div class="btn">Click Me</div>
</div>
<div id="output">

</div>

JS:

$(document).ready(function(){

  $('#main').on('mousemove',function( e ) {
  var msg = "mouse move ";
  msg += e.pageX + ", " + e.pageY;
  $( "#output" ).html(msg);
});

});

最佳答案

只需检查您的事件处理程序中的目标是谁,如果它是您要阻止事件的目标之一,请尽早返回。

在当前配置中,它与检查目标是否确实是 #main 相同,又名 jQuery's $event.currentTarget .

$('#main').on('mousemove', function(e) {
  // here we only want the events of #main
  // so any other target is irrelevant
  if (e.target !== e.currentTarget) return;
  var msg = "mouse move ";
  msg += e.pageX + ", " + e.pageY;
  $("#output").html(msg);
});
$('#main').on('mouseout', function() {
  $("#output").html('');
});
$('#main>.btn').on('click', e=> $("#output").html('can still click'));
#main {
  float: left;
  background: yellow;
  width: 400px;
  height: 400px;
  position: relative;
}

#main .btn {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 2;
  border: 0;
  background: blue;
  color: #FFF;
}

#main .btn .innerbtn {
  padding: 10px;
}

#output {
  display: inline-block;
  background: #efefef;
  width: 200px;
  position: absolute;
  right: 0;
  pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
  <div class="btn">
    <div class="innerbtn">Click Me</div>
  </div>
</div>
<div id="output">

</div>

关于javascript - 避免在绝对定位的子元素上移动鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54228432/

相关文章:

javascript - 如何在输入(文本区域)字段中输入多个值?

javascript - 创建复杂 JavaScript 形状的有效方法

javascript - 如何通过 javascript 导入 .ics 文件并返回议程

Javascript 如何返回包含奇数的数组

Java解析XML : getElementsByTagName returns all elements

javascript - 仅当 div 被隐藏时,如何在 div 上使用 angularjs $anchorScroll?

css - css中首字母大写,其他字母小写?

css - 使用 CSS 创建亚麻纹理?

php - Xpath 问题,如果您知道元素的标题,则获取元素的 id(属性)

javascript - 如何检查事件是否被阻止