Image change opacity on hover without jQuery

血红的双手。 提交于 2019-12-11 04:03:20

问题


I am trying to make a list of social buttons. When one button is hovered it lights up, and the other buttons should darken.

I got it to work partially. When the first button is hovered all works fine, but it is malfunctioning when the other buttons are hovered. I think this happens because all the latter list items are siblings of the first and the :hover event can't cause previous elements to change style. Does anyone have any thoughts on how to get this to work?

Here's the code (jsFiddle live demo):

<div id="bg">

<ul id="social_buttons">
    <li id="item_1"><img src="http://i43.tinypic.com/104rasi.png"></li>
    <li id="item_2"><img src="http://i43.tinypic.com/k4tide.png"></li>
    <li id="item_3"><img src="http://i44.tinypic.com/2ry0gt3.png"></li>
</ul>

</div>
#bg {
    height: 100px;
    width: 215px;
    background-color: black;
    position: relative;
}

#social_buttons img {
     width: 24px; 
     height: 24px;

    -webkit-transition:all 0.2s ease-in-out;
    -moz-transition:all 0.2s ease-in-out;
    -o-transition:all 0.2s ease-in-out;
    transition:all 0.2s ease-in-out;
}



#social_buttons {
    list-style-type: none;
    position: absolute;
    top: 20px;
    right: 70px;

    -webkit-transition:all 0.2s ease-in-out;
    -moz-transition:all 0.2s ease-in-out;
    -o-transition:all 0.2s ease-in-out;
    transition:all 0.2s ease-in-out;
}


#social_buttons li {
    float: left;
    margin-right: 2px;

    -webkit-transition:all 0.2s ease-in-out;
    -moz-transition:all 0.2s ease-in-out;
    -o-transition:all 0.2s ease-in-out;
    transition:all 0.2s ease-in-out;
}


/*  puur css3 multiple hover animaties */
#item_1 {
    opacity: 0.8;
}
#item_1:hover ~ #item_2, :hover ~ #item_3 {
    opacity: 0.5;
}
#item_1:hover {
    opacity: 0.9;
}


#item_2 {
    opacity: 0.8;
}
#item_2:hover ~ #item_1, :hover ~ #item_3 {
    opacity: 0.5;
}
#item_2:hover {
    opacity: 0.9;
}

#item_3 {
    opacity: 0.8;
}
#item_3:hover ~ #item_1, :hover ~ #item_2 {
    opacity: 0.5;
}
#item_3:hover {
    opacity: 0.9;
}

回答1:


This is actually pretty easy with the right selectors

jsFiddle

ul li {
    opacity: 0.8;
}

ul:hover li {
    opacity: 0.5;
}

ul li:hover {
    opacity: 1.0;
}



回答2:


Something like this?

#social_buttons:hover li {
    opacity: 0.5;
}

#social_buttons li:hover {
    opacity: 0.9;
}

General sibling selector (~) can't select preceding element, it works only in one direction.




回答3:


http://jsfiddle.net/VnMFP/4/

#social_buttons li {
    opacity: 0.8;
}

#social_buttons:hover li {
    opacity: 0.5;
}

#social_buttons li:hover {
    opacity: 0.9
}

Don't select the li:hover, select ul#social_buttons:hover li. Then it works.



来源:https://stackoverflow.com/questions/17435158/image-change-opacity-on-hover-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!