最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change the color of another link on hover? - Stack Overflow

programmeradmin5浏览0评论

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.)

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.)

Share Improve this question edited Nov 24, 2011 at 9:24 Kees C. Bakker 33.5k31 gold badges118 silver badges207 bronze badges asked Nov 24, 2011 at 8:55 RoyalEnfyRoyalEnfy 1271 silver badge11 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

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./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/9Ezt5/

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

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

Yes you can do it with pure css.

for example:

a:hover + a{
 background:red;
}

Check this for more

http://jsfiddle/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/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.

发布评论

评论列表(0)

  1. 暂无评论