CSS change an element content on hover from different element

主宰稳场 提交于 2020-01-02 05:02:29

问题


Is it possible in CSS to change an element's content when hovered from a different element? Let's say for example, I have this divs A, B, C, D, E, F. I want to show some text in A when I hover in B. a different text will appear in A if I hover over in C. and the same goes for the rest. All the changes takes place in A when hovered in divs B to F.


回答1:


Currently this is not possible with CSS only. You can adjust the styles of children or upcoming siblings. But you can't set the styles of previous siblings or parent elements.

So regarding your case you could do:

<div class="a"></div>
<div class="b"></div>
<div class="c"></div>

CSS

/* next sibling only */
div.a:hover + div.b { /* styles for b when hovering a */ }

/* general sibling selector */
div.a:hover ~ div.c { /* styles for c when hovering a */ }
div.b:hover ~ div.c { /* styles for c when hovering b */ }

You can't go the other way, from b to a for example.

Demo

Try before buy




回答2:


This is possible using the general sibling selector ~ and by having a matching div to go with each of the hovered divs. This works in the latest version of all browsers. http://jsfiddle.net/s8uwu/

HTML

<div id="a">Hello A</div>
<div id="b">Hello B</div>
<div id="c">Hello C</div>
<div id="d">Hello D</div>
<div id="e">Hello E</div>
<div id="text">
    <div class="a">From A</div>
    <div class="b">From B</div>
    <div class="c">From C</div>
    <div class="d">From D</div>
    <div class="e">From E</div>
</div>

CSS

#a:hover~#text .a,
#b:hover~#text .b,
#c:hover~#text .c,
#d:hover~#text .d,
#e:hover~#text .e{
    display: block;
}

#text div{
    display: none;
}



回答3:


Simply from its name, CSS(Cascading Style Sheet) is only for applying style/appearance in a convenient way.

Hence it does not at all deal with the content of an web-page.

However You definitely can do it with the help of JavaScript as follows-

<div id="a" onmouseover="document.getElementById('b').innerHTML='ijkl';">abcd</div>
<div id="b">efgh</div>


来源:https://stackoverflow.com/questions/19121223/css-change-an-element-content-on-hover-from-different-element

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