[英]Affecting only the hovered children without the parents
The following code adding a red shadow on every DOM element on hover, how can i mark only that element what is under the cursor? 以下代码在悬停时的每个DOM元素上添加了一个红色阴影,如何仅标记该元素在光标下方?
$( "html *" ).hover(function() {
$( this ).css('box-shadow','inset 0 0 3px red');
}, function() {
$( this ).css('box-shadow','none');
}
);
});
Here is my jsfiddle: https://jsfiddle.net/eapo/7Lyt9qeb/2/ 这是我的jsfiddle: https ://jsfiddle.net/eapo/7Lyt9qeb/2/
You want to take a look at document.elementFromPoint 您想看一下document.elementFromPoint
Using the mousemove
event, the target
is what you are after 使用mousemove
事件, target
就是您要追求的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>
Instead of :hover
, I suggest adding two delegated event listeners: 建议不要添加:hover
,而是添加两个委托的事件侦听器:
mouseenter
event listener to detect when an element enters an element. 一个mouseenter
事件侦听器,用于检测元素何时进入元素。 It doesn't bubble, so it will only be invoked on the deepest hovered element. 它不会冒泡,因此只会在最深的悬停元素上调用。 mouseout
event listener. mouseout
事件侦听器。 This event happens even when the mouse moves from an element to a descendant. 即使鼠标从元素移到后代,也会发生此事件。 $("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 is not needed for this use the css selector last-child with hover 为此,无需使用JavaScript,就可以将css选择器last-child和hover一起使用
body:last-child:hover {
background: #ff0000;
}
Edit I misunderstood your question this is not possible with just css here is a jQuery selector to get the most deepest element. 编辑我误解了您的问题,仅使用CSS是不可能的,这是获得最深层元素的jQuery选择器。
$('body *:not(:has("*"))');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.