Show child div on mouse hover of parent - needs ja

2020-05-19 04:02发布

I need to show a div when you house over its parent (default is for the child div to be hidden). Is the only way to do this with javascript? Thanks

7条回答
We Are One
2楼-- · 2020-05-19 04:28

Using jQuery you can add a mouseover event to the parent div, and show the child div. See this fiddle as an example.

查看更多
SAY GOODBYE
3楼-- · 2020-05-19 04:32

@jdln; yes

css:

.outer {
    background:red;
    height:100px;
}
.box1 {
    background:blue;
    height:100px;
    width:80px;
    display:none;
}
.outer:hover .box1{
    display:block;
    cursor:pointer;
}

check the fiddle: http://jsfiddle.net/sandeep/XLTV3/1/

查看更多
甜甜的少女心
4楼-- · 2020-05-19 04:44

I initially was using css solution above, but had to use jQuery because my child div contained an image which caused hover to flicker. Here we're displaying child when hovering over parent (if desktop screen size) on mouseenter and hiding it on mouseleave but only if now hovering over main page container, to minimize flickering:

$(document).ready(function () {
    $(".parent-qtip").mouseenter(function () {
        if ($(window).width()>=1200)
            $(this).children(".child-qtip").show();
    });
    $(".parent-qtip").mouseleave(function () {
        if ($('.page-content').find('.container:hover').length)
            $('.child-qtip').hide();
    });
});
查看更多
混吃等死
5楼-- · 2020-05-19 04:47

In addition to the accepted answer, one can use opacity so that layout is not jumping around on hover (this also allows to animate the appearance):

css:

.show-on-hover-parent:hover .show-on-hover-item {
    opacity: 1;
   //transition: opacity .5s; //<- optional opacity animation
}

.show-on-hover-parent .show-on-hover-item {
    opacity: 0;
   //transition: opacity .5s; //<- optional opacity animation
}

html:

<div class="show-on-hover-parent">
    <div>Always visible 1</div>
    <div class="show-on-hover-item">visible on hover</div>
    <div>Always visible 2</div>
</div>
查看更多
够拽才男人
6楼-- · 2020-05-19 04:48

With jQuery, absolutely:

$("#some_parent").hover(function ()
{
    $(this).children("#some_child_div").show();
});
查看更多
We Are One
7楼-- · 2020-05-19 04:49

No JS required.

.hidden {
  display: none;
}

.parent:hover .hidden {
  display: block;
}
<div class="parent">
  <p>Hello, I'm a child...</p>
  <p class="hidden">..and so am I but I'm hidden.</p>
</div>

查看更多
登录 后发表回答