Making an element visible by hovering another elem

2020-03-07 17:46发布

Okay, here's the problem:

i have these three DIVs:

<div id="gestaltung_cd"></div>
<div id="gestaltung_illu"></div>
<div id="gestaltung_klassisch"></div>

…and these three DIVs – which are invisible (display:none;)– on a completely different position on the page:

<div id="mainhexa1"></div>
<div id="mainhexa2"></div>
<div id="mainhexa3"></div>

what i want to do is: if i hover "gestaltung_cd" i want to make "mainhexa1" visible and if i hover "gestaltung_illu" i want to make "mainhexa2" visbile and so on…

as you can see, the three invisible DIVs are no child-elements of the first three ones... so ":hover" is not possible in this case. Is there an easy way to do this in JQuery?

thanks, Jochen

8条回答
\"骚年 ilove
2楼-- · 2020-03-07 18:14

You could use the sibling selector. As long as div's share the same parent, you can still affect them with hover

DEMO

Vital Code:

#gestaltung_cd:hover ~ #mainhexa1,
#gestaltung_illu:hover ~ #mainhexa2,
#gestaltung_klassisch:hover ~ #mainhexa3 {
    display: block;
}
查看更多
再贱就再见
3楼-- · 2020-03-07 18:14

I'd suggest you add an attribute to the first three divs that specifies which div to show on hover:

<div id="gestaltung_cd" data-maindiv="mainhexa1"></div>
<div id="gestaltung_illu" data-maindiv="mainhexa2"></div>
<div id="gestaltung_klassisch" data-maindiv="mainhexa3"></div>

That way you can handle the show/hide on hover with a single use of the .hover() method:

$("div[data-maindiv]").hover(function() {
    $("#" + $(this).attr("data-maindiv") ).show();
},
function() {
    $("#" + $(this).attr("data-maindiv") ).hide();
});

Demo: http://jsfiddle.net/GFMQR/

查看更多
登录 后发表回答