在父级鼠标悬停时显示子 div - 需要 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6305141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show child div on mouse hover of parent - needs javascript?
提问by Evanss
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
当你把它放在父级上时,我需要显示一个 div(默认是隐藏子 div)。是用 javascript 做到这一点的唯一方法吗?谢谢
回答by Marcel
No JS required.
不需要JS。
.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>
回答by sandeep
@jdln; yes
@jdln; 是的
css:
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/
回答by Dormouse
With jQuery, absolutely:
使用 jQuery,绝对:
$("#some_parent").hover(function ()
{
$(this).children("#some_child_div").show();
});
回答by boateng
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:
我最初使用上面的 css 解决方案,但不得不使用 jQuery,因为我的子 div 包含导致悬停闪烁的图像。在这里,我们在 mouseenter 上悬停在父级(如果桌面屏幕大小)上并在 mouseleave 上隐藏它时显示子级,但前提是现在悬停在主页容器上,以最大程度地减少闪烁:
$(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();
});
});
回答by vir us
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):
除了接受的答案之外,还可以使用opacity
这样布局不会在悬停时跳跃(这也允许为外观设置动画):
css:
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:
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>
回答by Uphill_ What '1
回答by James Allardice
Using jQuery you can add a mouseover
event to the parent div, and show
the child div. See this fiddleas an example.
使用 jQuery,您可以将mouseover
事件添加到父 div 和show
子 div。以这个小提琴为例。