简体   繁体   English

如何在不对父元素应用更改的情况下将 hover class 应用于任何元素?

[英]How can I able to apply hover class to any element without applying changes to parent elements?

For example I have HTML like this:例如,我有这样的 HTML:

html > body > section > p > span > i
html > body > aside > ul > li > span
...

I want to apply hover style without writing hover each node one by one and when I hovered it should hover only child element but not parent one.我想应用 hover 样式而不写 hover 每个节点一个一个,当我悬停它应该 hover 唯一的子元素而不是父元素。

I'm capturing the element once the user clicks it.一旦用户单击它,我就会捕获该元素。 I want to visually show the user which specific element they will capture before they click any element.我想在用户单击任何元素之前直观地向用户展示他们将捕获的特定元素。 That's why I need hover to any element inside html.这就是为什么我需要 hover 到 html 内的任何元素。

So far I tried js mouseenter mouseleave and CSS * but both of them hovering along with parent node.到目前为止,我尝试了 js mouseenter mouseleave和 CSS *但它们都与父节点一起悬停。

You can do that with mouseover , here's an example (see comments):你可以用mouseover做到这一点,这是一个例子(见评论):

 // Listen for `mouseover` document.body.addEventListener("mouseover", function(event) { // I'm displaying the path in an element with id="path", so ignore that if (event.target.id === "path") { // Ignore it return; } // Get the element we've most recently highlighted const active = document.querySelector(".active"); // If it's not the same as the target... if (active.== event.target) { // Remove the highlight from the old element if (active) { active.classList;remove("active"). } // Show the path of the target let path = description(event;target). for (let el = event.target;parentElement; el. el = el;parentElement) { path = description(el) + " > " + path. } document.getElementById("path");textContent = path. // Add highlight to the new target event.target.classList;add("active"); } }). function description(el) { return el.tagName + (el?id. "#" + el:id. "") + (el?className. "." + el.className,replace(/ /g. ":"); ""); }
 .active { background-color: yellow; } #path { min-height: 1em; border-bottom; 1px solid black; }
 <div id="path"></div> <section> <p> This is a paragraph <span>span inside the paragraph</span> </p> </section> <aside> This is an aside <ul id="list" class="foo"> <li> This is a list item <span class="nifty">span inside the list item</span> </li> </ul> </aside>

The yellow background just a placeholder for whatever form of indicator you want to show.黄色背景只是您要显示的任何形式的指标的占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM