简体   繁体   中英

How to change the color of another link on hover?

This is the simple HTML code:

<li class="main">
<a href="#">ImageLink</a> <!--1st anchor tag-->
<a href="#">ImageName</a> <!--2nd anchor tag-->
</li>

Is it possible to change the color of 2nd anchor tag on hover state of 1st anchor tag? (And vice versa.)

Not with css. This kind of actions can only be done by script.

If you use jQuery you could add the following script:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript>

        $(document).ready(function(){

            var a1 = $('a:first');
            var a2 = $('a:second');

            a1.hover(function(){ a2.toggleClass('hover') }, function(){ a2.toggleClass('hover') });
            a2.hover(function(){ a1.toggleClass('hover') }, function(){ a1.toggleClass('hover') });

        });
</script>

Now you can use the hover class to specify the color:

.hover { color: red; }

Edit It would be easier to give both a 's an id, so you could reference them by using var a1 = $('#a1'); .

With CSS, it's possible to change the color of the 2nd anchor tag on hover of the 1st anchor tag with a sibling selector, but I don't think you can do it vice-versa:

a:hover + a {
    color: red;
}

JSFiddle preview: http://jsfiddle.net/9Ezt5/

See http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors

However, note that adjacent sibling selectors are not supported on all browsers: http://www.quirksmode.org/css/contents.html

Yes you can do it with pure css.

for example:

a:hover + a{
 background:red;
}

Check this for more

http://jsfiddle.net/Bw5by/

In Jquery you can do it like this,

$("#first").hover(function(){
    $('#second').css('color','red')
    },function(){
    $('#second').css('color','blue')
    });

See it in action here,

http://jsfiddle.net/gagan/NYAHY/1/

If those are the only two links in the list item tag, then you could do something like this:

li.main:hover a
{
    color: red;
}

li.main a:hover
{
    color: blue;
}

Then your hovered link will be blue, and all the other ones (in this case just that other one) will be red.

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.

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