- 首页
- 前端开发
- CSS悬停 - 它可以影响具有相同类名的多个div
CSS悬停 - 它可以影响具有相同类名的多个div
[英] CSS hover - can it effect multiple divs with same class name
本文介绍了CSS悬停 - 它可以影响具有相同类名的多个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有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而不只是有问题的更改...
我无法将它们包装在父对象中,并且让父对象徘徊。
CSS是否提供了一种方法来实现这一点,或者我要停留在JavaScript?
$ c>和 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 els [i] .addEventListener('mouseover',function(e){
classToggle(e,'test','highlight');
});
els [i] .addEventListener('mouseout',function(e){
classToggle(e,'test','highlight');
}
}
JS Fiddle demo 。
参考文献:
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?
解决方案
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:
这篇关于CSS悬停 - 它可以影响具有相同类名的多个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!