我有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().更多推荐
发布评论