I have searched everywhere yet everything seems to skirt around what I am after and I haven't learnt enough to do this myself so sorry if it is out there somewhere or a stupid question.
This is my current structure below:
<nav>
<ul>
<li><a href="#">Home</a></li>
<li class="select"></li>
<li><a href="#">Services</a></li>
<li class="noselect"></li>
<li><a href="#">Gallery</a></li>
<li class="noselect"></li>
<li><a href="#">About Us</a></li>
<li class="noselect"></li>
<li><a href="#">Contact Us</a></li>
<li class="noselect"></li>
</ul>
</nav>
What I want is when a link is hovered, the 'li' that follows has it's class changed to 'select' and all others set to 'noselect'.
I have included a jsfiddle so you can see what I mean. (Found here )
Thanks in advance, Swift
You can do this without resorting to javascript. In plain css:
nav:hover .select {
background:#ff0000;
}
nav li:not(.select):hover + li {
background:#000;
}
Here's a fiddle http://jsfiddle.net/2Ua2a/9/
I'd probably, however, simplify it to this: http://jsfiddle.net/58gNm/2/ - just keeps the html cleaner.
$('li a').on('mouseenter mouseleave', function() {
$(this).closest('li').next('li').addClass('select')
.siblings('li').removeClass('select');
});
You don't have to toggle two classes, just make sure the select
class has a more specific selector than the noselect
class, and it will override it.
Check this fiddle:
http://jsfiddle.net/BuddhiP/2Ua2a/6/
$(function() {
$('a').on('hover', function() { $(this).parent().next('li').toggleClass('select noselect') });
});
Here you go:
$('a').on('hover', function(){
var $parent = $(this).parent('li');
$parent.siblings('li.select').removeClass('select').addClass('noselect');
$parent.next('li').removeClass('noselect').addClass('select');
});
The code is simple. When hovering a link, I run a funcion. First I declare the parent li
as a variable because it's easier to read and slightly better for performance.
I then target the sibling, which currently have the .select
-class, and make it unselected. Lastly, I simply add the class to the immediatly following li
.
See the fiddle: http://jsfiddle.net/2Ua2a/5/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.