2014-07-10 88 views
4

我正在尋找一個解決方案,以便如何設置彈出div的位置,這是通過點擊另一個div顯示的,但其位置取決於窗口位置在哪裏。設置動態彈出div的位置

這裏我的div的一些例子:

<div id="header"></div> 

<div id="open">Click here to open the popup</div> 

<div id="popup"> 
     <div class="popup-wrapper"> 
      <div class="content"> 
      <h1>TEST</h1> 
      </div> 
     </div> 
</div> 

<div id="footer"></div> 

例如:

  1. 如果用戶點擊#open div來顯示#popup DIV與瀏覽器的窗口滾動的位置在底部欄中,我希望#popup div顯示在#open div的頂部。

  2. 然而,如果用戶點擊「#open」 div來顯示#popup DIV與瀏覽器的頂部窗口的位置,我想那#popup div來在#open div的底部顯示。

這裏是我使用的腳本:

$("#popup").click(function(e) { 
    if ($(e.target).closest(".content" /*or any other selector here*/).length > 0){ 
     return false; 
    } 
    $("#popup").fadeOut(200); 
    $("body").addClass("no-scroll"); 
}); 

//This is just to open the popup 
$('#open').click(function() { 
    $("#popup").show(); 
}); 

這裏是CSS FIDDLE

+2

您可以檢查滾動條的位置並相應地顯示彈出窗口。 – u54r

回答

2

完整的代碼檢查用戶的滾動條位置。然後根據滾動條的位置顯示彈出窗口。沒有測試過下面的代碼,但是類似於這個。

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; 

if(scrollTop == 0){ 
    // Window on top. Display popup 
} 

if(scrollTop == $(window).height()){ 
    // Window on bottom. Display popup 
} 
+0

請看下面我張貼在這個頁面的截圖。 – inandout

0

你可以得到event.offsetX和event.offsetY了「#open」 DIV位置點擊DIV時,那麼你就可以計算出新的座標彈出窗口。

+0

你能給我舉一個如何安排代碼的例子。並請看看我張貼在這個頁面的一些screnshots。提前致謝。 – inandout

1

這是一個更加動態的工作解決方案。它查找具有'popupSection'類的任何元素並打開它的彈出窗口。

$('.popupSection').on('click',function(e){ 
    var target = $(e.target); 
    var targetOffset = target.offset().top; 
    var scrollPosition = $(window).scrollTop(); 
    if (scrollPosition <= targetOffset) { 
     openPopup(targetOffset); 
    } else { 
     var targetHeight = target.height(); 
     var contentHeight = $('#popup .content').outerHeight(); 
     var targetBottomOffset = targetOffset + targetHeight - contentHeight; 
     openPopup(targetBottomOffset); 
    }  
}); 

var openPopup = function(offset){ 
    var popup = $('#popup'); 
    var popupContent = $('#popup .content'); 
    if (popup.css('display') === 'none') { 
     popup.css('display','block'); 
    } 
    popupContent.css('top',offset);  
} 

$("#popup").click(function(e) {  
    $("#popup").fadeOut(200); 
}); 

工作小提琴:http://jsfiddle.net/epbdZ/2/

+0

幾乎在那裏,但是當用戶單擊開始的彈出div時,它不會關閉div。 http://jsfiddle.net/Alkasih/76exm/我更新你的小提琴。 – inandout

+0

這裏是一個更新的小提琴,當用戶在彈出窗口外單擊時關閉彈出窗口:http://jsfiddle.net/76exm/1/ – charliegeiger89

+0

我發現代碼仍然不能按照我的需要工作。這裏是場景:在小提琴中,有兩種顏色,黃色和灰色。如果「灰色div」位於窗口的底部,我希望彈出div顯示在該灰色的上層。但是,如果灰色位於窗口的頂部,我希望'彈出div'顯示在灰色的波紋管中。請。 – inandout