Can't change background-color of another eleme

2019-08-24 04:06发布

问题:

I've created a list with elements. I want the background color of #tags_image to change to yellow when you hover element 1, to blue when you hover element 2, etc. This is my HTML code:

<ul id="tags">
    <li><div id="tag1">Familie</div></li>
    <li><div id="tag2">Uncharted</div></li>
</ul>
<div id="tags_image"><img src="images/transparent.png" width="100%"></div>

And my CSS:

#tags {
    padding: 4px;
    display: inline-block;
}

#tags_image {
    display: inline-block;
    margin-left: 7.5%;
    width: 20%;
    background-color: red;
}

#tags li {
    display: inline;
    cursor: pointer;
}

#tags #tag1:hover + #tags_image {
background-color: yellow;
}

#tags #tag2:hover + #tags_image {
background-color: blue;
}

However, this doesn't seem to work. The problem is not with the :hover attribute, because I can change elements of tag1 and tag2 this way, but I can't change the elements of #tags_image.

How can I fix this? Any help would be much appreciated!

回答1:

You can use jQuery to manipulate this.

$("#tag1").hover(function(){
    $("#tags_image").css('background','yellow');
});

$("#tag2").hover(function(){
    $("#tags_image").css('background','blue');
});

CMIIW~