<div class="parent">
<strong>I function as a hover trigger</strong>
<div class="child">I am a child</div>
</div>
... // More number of <div> Skipping for reducing the number of lines
<div class="parent">
<strong>I function as a hover trigger</strong>
<div class="child">I am a child</div>
</div>
CSS
.parent{
display:block;
width:150px;
position:relative;
}
.child{
position: absolute;
display: none;
top:0;
right:148px;
}
剧本
$('.parent').mouseenter(function(e) {
$(this).find('.child').css({"display": "block"});
});
$('.parent').mouseleave(function(e) {
$(this).find('.child').css({"display": "none"});
});
如果父{1}}悬停,则会显示子<div>
。孩子的位置与父母有关。但是如何调整位置,以便如果孩子溢出视口,则需要将其推高。通常,与顶级父<div>
对应的子级不会从视口溢出,而底部父级<div>
的子级会溢出。
答案 0 :(得分:3)
由于您使用jQuery,您可以简单地计算所需的偏移量
$('.parent').mouseenter(function(e) {
var $child = $(this).find('.child');
$child.css({"display": "block"});
var offset = $child.offset();
if (offset.top + $child.height() > $(window).height()) {
var top = $child.height() - $(this).height();
$child.css({'top': '-' + top + 'px'});
}
});
这看起来,如果孩子的底部溢出视口并将孩子所需的偏移更高。
查看完整的JSFiddle
答案 1 :(得分:2)
您好,如果子元素溢出视口,您可以设置和if
语句计算:
//Calculate the height of the window
var wh = $(window).height();
//Begin Hover function
$('.parent').hover(function(e) {
//Calculate height of child and position from the top of viewport
var ch = $(this).find('.child').outerHeight(),
ct = $(this).offset().top - $(window).scrollTop(),
diff = ch + ct;
//If that value are more than window height then change position of children
if (diff > wh) {
$(this).find('.child').css({'top':'auto','bottom':'0'})
}
$(this).find('.child').css({"display": "block"});
}, function(e) {
$(this).find('.child').css({"display": "none"});
//Remove position after leave parent
$(this).find('.child').attr('style','');
});