2014-01-30 2 views
0
<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"}); 
}); 

Ребенок <div> будет появляться, если родитель <div> наведен. И положение ребенка в отношении родителя. Но как можно настроить положение так, что если ребенок переполняет окно просмотра, его нужно подтолкнуть вверх. Обычно дочерний элемент, соответствующий верхнему родителю <div>, не переполняется из окна просмотра, тогда как дочерние элементы нижнего родителя <div> получают переполнение.

enter image description here

ответ

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

+0

Будет ли это работать в IE? Моя версия IE - 11 и кажется, что ребенок не появляется. Но работает как ожидается в Chrome и Firefox. –

+0

Я нахожусь в Linux, поэтому я не могу комментировать IE. –

+0

Да, хорошо. И в IE ребенок появляется с jQuery версии 1.9.1 и не с 1.10.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',''); 
}); 

Проверить это демо http://jsfiddle.net/P7NPd/2/

Смежные вопросы