CSS悬停

编程入门 行业动态 更新时间:2024-10-23 01:58:34
CSS悬停 - 它可以影响具有相同类名的多个div(CSS hover - can it effect multiple divs with same class name)

我有5个div都具有相同的类名,如下所示:

CSS:

.test:hover{ color:red; }

HTML:

<div class="test"></div> <div class="test"></div> <div class="test"></div> <div class="test"></div> <div class="test"></div>

想象一下这些Div在页面上的不同父级div ...

我正试图找到一种方式,所以它们都变成了color:red如果我将鼠标悬停在5个中的任何一个而不仅仅是改变的那个中,那么就是color:red ......

我无法将它们包装在父母中,并且让父母一直悬停......他们首先不会共享同一个父母。

CSS是否提供了这样做的方法,或者我将不得不休息到JavaScript?

I have 5 div's all with the same class name like this:

CSS:

.test:hover{ color:red; }

HTML:

<div class="test"></div> <div class="test"></div> <div class="test"></div> <div class="test"></div> <div class="test"></div>

Imagine for a moment these Div's are in different parent div's on the page...

I'm trying to find a way so they all change to color:red if i hover my mouse over any of the 5 rather than just the one in question changing...

I can't wrap them in a parent and give that parent a hover how ever... they are not sharing the same parents in the first place.

Does CSS provide a way to do this or am I going to have to rest to JavaScript?

最满意答案

一个(普通/普通)JavaScript方法(在兼容的浏览器中,支持[].forEach()和document.querySelectorAll() ),因为CSS 不能 (还)执行此任务,是:

function classToggle (evt, find, toggle) { [].forEach.call(document.querySelectorAll('.' + find), function(a){ a.classList[evt.type === 'mouseover' ? 'add' : 'remove'](toggle); }); } var els = document.querySelectorAll('.test'); for (var i = 0, len = els.length; i<len; i++){ els[i].addEventListener('mouseover', function(e){ classToggle(e, 'test', 'highlight'); }); els[i].addEventListener('mouseout', function(e){ classToggle(e, 'test', 'highlight'); }); }

JS小提琴演示 。

参考文献:

Array.prototype.forEach() 。 document.querySelectorAll() 。 Element.classList 。 Function.prototype.call() 。

One (plain/vanilla) JavaScript approach that works (in compliant browsers, which support [].forEach(), and document.querySelectorAll()), given that CSS cannot (yet) perform this task, is:

function classToggle (evt, find, toggle) { [].forEach.call(document.querySelectorAll('.' + find), function(a){ a.classList[evt.type === 'mouseover' ? 'add' : 'remove'](toggle); }); } var els = document.querySelectorAll('.test'); for (var i = 0, len = els.length; i<len; i++){ els[i].addEventListener('mouseover', function(e){ classToggle(e, 'test', 'highlight'); }); els[i].addEventListener('mouseout', function(e){ classToggle(e, 'test', 'highlight'); }); }

JS Fiddle demo.

References:

Array.prototype.forEach(). document.querySelectorAll(). Element.classList. Function.prototype.call().

更多推荐

本文发布于:2023-07-16 07:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1125488.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CSS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!