jQuery - Display an element on hover of another

回眸只為那壹抹淺笑 提交于 2019-12-02 16:28:14

问题


This could be done easily in CSS if the element that needs to be displayed was a child of the hover, but it isn't; it's in a different section of the document.

I'm trying to have the menu display upon hovering over the '[ + ]' element.

Live: http://blnr.org/testing

Jfiddle: http://jsfiddle.net/bUqKq/5/

jQuery:

$(document).ready(function(){
    $("header[role='masthead'] #container #left nav#static span").hover(
        function(){$("header[role='masthead'] nav#active").show();},
    );
});

回答1:


You can drastically simplify this by just only showing the id's you are interested in. No need for the rest of the selectors that you are using as ID's are required to be unique. Note I also provided both hover-in and hover-out functions as I am assuming you want to hide the element after hover condition ends.

    $(document).ready(function(){
        $("#static span").hover(
            function(){
                $("#active").show();
            },
            function(){
                $("#active").hide();
            }
        );
    });

Alternately you could just us single closure with toggle() like this:

    $(document).ready(function(){
        $("#static span").hover(
            function(){
                $("#active").toggle();
            }
        );
    });



回答2:


Here is a simple example where you hover over one element and a completely different element is changed,

http://jsfiddle.net/bUqKq/6/

<div id="one">hover here</div>
<div id="two">hover here2</div>

 

$("#one").on("mouseover",function(){
    $("#two").css({
        color:"red"
    })
});

$("#one").on("mouseout",function(){
    $("#two").css({
        color:"black"
    })
});

$("#two").on("mouseover",function(){
    $("#one").css({
        color:"red"
    })
});


$("#two").on("mouseout",function(){
    $("#one").css({
        color:"black"
    })
});


来源:https://stackoverflow.com/questions/17437133/jquery-display-an-element-on-hover-of-another

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