只影响没有父母的孩子

Affecting only the hovered children without the parents

本文关键字:孩子 父母 影响      更新时间:2023-09-26

下面的代码在每个DOM元素上添加一个红色的阴影,我如何才能只标记光标下的元素?

$( "html *" ).hover(function() {
      $( this ).css('box-shadow','inset 0 0 3px red');
    }, function() {
      $( this ).css('box-shadow','none');
    }
  );
});

这是我的jsfiddle: https://jsfiddle.net/eapo/7Lyt9qeb/2/

您需要查看document.elementFromPoint


使用mousemove事件,target是您在

之后的内容

document.body.addEventListener("mousemove",function(e){
  // clear "hovered" class
  var elems = document.getElementsByClassName("hovered");
  for(var a=elems.length-1; a>=0; a--){elems[a].classList.remove("hovered");}
  //add "hovered" class to target
  e.target.classList.add("hovered");
});
div{
  display:inline-block;
  outline: 1px solid;
  font-size:0px;
  width:50%;
  height:50%;
}
div.hovered{
  background-color:rgba(255,0,0,0.5);
}
body{
  width:400px;
  height:400px;
}
<body>
<div>
  <div>
    <div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </div>
  <div>
    <div></div>
  </div>
</div>
</body>

代替:hover,我建议添加两个委托事件侦听器:

  • mouseenter事件监听器,用于检测元素何时进入元素。它不会冒泡,所以它只会在最深的悬停元素上被调用。
  • mouseout事件监听器。当鼠标从一个元素移动到它的后代元素时,这个事件也会发生。

$("html").on('mouseenter', '*', function() {
  this.style.boxShadow = 'inset 0 0 5px red';
}).on('mouseout', '*', function(e) {
  this.style.boxShadow = '';
  console.log(e.target);
});
body {
  width: 400px;
}
div {
  min-height: 20px;
  border: 1px solid;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>
    <div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </div>
  <div>
    <div></div>
  </div>
</div>

不需要JavaScript,使用css选择器last-child with hover

body:last-child:hover {
    background: #ff0000;
}

编辑我误解了你的问题,这是不可能的,只是css这里是一个jQuery选择器,以获得最深的元素。

$('body *:not(:has("*"))');