[英]Set the position of pop up div dynamically
我正在尋找一個解決方案,如何設置彈出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>
例如:
如果用戶點擊#open
div來顯示#popup
在底部的瀏覽器窗口滾動條的位置格,我想那#popup
div來在頂部顯示#open
股利。
但是,如果用戶點擊“#open” div來顯示#popup
與瀏覽器的頂部窗口的位置格,我想那#popup
div來在底部顯示#open
格。
這是我使用的腳本:
$("#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的完整代碼
檢查用戶的滾動條位置。 然后根據滾動條的位置顯示彈出窗口。 沒有測試下面的代碼,但有類似的東西。
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
}
這是一個更加動態的工作解決方案。 它查找具有'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/
單擊div時,可以使用event.offsetX和event.offsetY獲取“#open”div位置,然后可以計算彈出窗口的新坐標。
一種方法不是通過燈箱div,但我可以使用帶有翻轉功能和鏡像功能的下拉式自動位置,如下所述: https : //github.com/twbs/bootstrap/issues/10756#issuecomment- 41041800
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.