Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

html - Show div when hover another div using only css

I have searched the web for this one but didn't find anything similar.

Say we have div A and div B. When hover on div A, div b should be visible ON (should look like overwriting) div A and not placed under.

It should appear like only the content of div A has changed to content of div B.

How can this be done in pure CSS and HTML?

#container > div {
    display: none
}
#container > div:first-child {
    display: block
}
#container > div:hover + div {
    display: block

<div id="container">
    <div>A</div>
    <div>B</div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will work, but only if the two divs are adjacent and b follows a.

#a:hover + #b {
    background: #f00
}

<div id="a">Div A</div>
<div id="b">Div B</div>

If you have divs in between use ~

#a:hover ~ #b {
    background: #f00
}

<div id="a">Div A</div>
<div id="c">Div C</div>
<div id="b">Div B</div>

To go the other way around, unfortunately you will need Javascript

// Pure Javascript
document.getElementById('b').onmouseover = function(){
    document.getElementById('a').style.backgroundColor = '#f00';
}
document.getElementById('b').onmouseout = function(){
    document.getElementById('a').style.backgroundColor = '';
}

// jQuery
$('#b').hover(
  function(){$('#a').css('background', '#F00')}, 
  function(){$('#a').css('background', '')}
);

Full fiddle http://jsfiddle.net/p7hLL/5/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...