2014-07-10 89 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