[英]Apply hover effect to child div only, without affecting parents with same class
[英]Affecting only the hovered children without the parents
以下代碼在懸停時的每個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
就是您要追求的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和hover一起使用
body:last-child:hover {
background: #ff0000;
}
編輯我誤解了您的問題,僅使用CSS是不可能的,這是獲得最深層元素的jQuery選擇器。
$('body *:not(:has("*"))');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.