DIV内滚动鼠标滚轮不触发鼠标事件刷新

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

我知道有人问过这个问题的变体,但我既找不到解决方案,也找不到解释为什么在这些问题中会发生这种情况。

考虑一个带有滚动条的父 DIV。在该 div 中,有一个在鼠标悬停事件时触发的其他 div 的列表。如果我使用鼠标 滚轮滚动父 div,鼠标悬停事件不会为子级触发,但是当我物理移动鼠标时,它会刷新并重新计算坐标并重新捕获鼠标悬停事件。

我尝试从代码触发 mousemove 事件 - 从文档到特定元素,但没有任何变化,我无法模拟物理鼠标移动坐标刷新行为。

浏览器中的物理鼠标移动会触发什么,以便我重新计算父 DIV 内的坐标?我可以从代码中调用刷新吗?

采用下面的代码,您可以看到用滚轮滚动不会触发悬停,但是当您移动鼠标时,即使是一点点事件也会刷新。

jQuery(document).ready(()=>{
let p = jQuery('.parent_div');
var c;
for(let i=0;i<20;i++)
{
  c = Math.floor(Math.random()*16777215).toString(16);
  p.append('<div class="child_div" style="background-color:#'+c+'"></div>') 
}
});
.parent_div
{
height: 100px;
overflow-y:scroll;
background-color:red;
}

.extra_parent_div
{
padding:50px;
}

.child_div
{
  height:40px;
  width:100%;
  cursor:pointer;
}

.child_div:hover
{
  background-color:white !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="extra_parent_div">
<div class="parent_div">
</div>
</div>

javascript html jquery css browser
1个回答
0
投票

可能的解决方案之一,您可以使用 .elementFromPoint() 突出显示 '.child_div' 给定

.scrollTop()
和值
clientY
上一个事件
mousemove
。 像这样的东西:

if( $('.parent_div').length ) {
  for(let i = 0; i < 20; i++) {
    const color = Math.floor( Math.random()*16777215 ).toString(16);
    $('.parent_div').append(`<div class="child_div" style="background-color:#${color}"></div>`) 
  }

  let x = 0;
  let y = 0;

  $('.parent_div').on('scroll', function() {
    highlight($(this));
  })

  $(window).on('scroll', function(event) {
    highlight($(this));
  })

  $(window).on('mousemove', function(event) {
    x = event.clientX;
    y = event.clientY;
  })

  function highlight(target) {
    $('.child_div').removeClass('active');
    const yPoint = y + target.scrollTop();
    const elFromPoint = document.elementFromPoint(x, y);
    $(elFromPoint).addClass('active');
  }

  $(document).on('mouseenter', '.child_div', function() {
    $('.child_div').removeClass('active');
    $(this).addClass('active');
  })

  $(document).on('mouseleave', '.child_div', function() {
    $('.child_div').removeClass('active');
  })
}
.parent_div {
  height: 400px;
  overflow-y: scroll;
  background-color: red;
}

.extra_parent_div {
  padding: 50px;
}

.child_div {
  height: 40px;
  width: 100%;
  cursor: pointer;
}

.child_div.active {
  background-color: white !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="parent_div"></div>

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