2009-09-15 33 views
0

我期待解構一些JavaScript,我發現一個網站上的一個燈箱插件。定位DIV

我很好奇,如果有人能幫助解碼這段腳本?我想實現它到我的jQuery中,但需要辨別我可以使用什麼我不能。

目前我的問題是,我的定位jQuery將我的div對齊到初始加載時看到的文檔的垂直中心。因此,如果向下滾動頁面一半,然後單擊某個項目以彈出窗口,則會將相對於文檔頂部的彈出框加載到某處,而不是相對於視口中心加載,而不管文檔的位置。另外,如果它對於屏幕來說太大了,它將會在中間加載,並且頂部和底部將被切斷,使得這些部分不可見,而如果這個javascript我發現它將會從頂部定位彈出div 10px,如果它太大。

找到的Javascript:

//Vertical position of div element: Either centered, or if element height larger than viewpoint height, 10px from top of viewpoint 
var scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset 
var topposition=(docheight>objheight)? scroll_top+docheight/2-objheight/2+"px" : scroll_top+10+"px" 
var docwidth=(ie)? this.standardbody.clientWidth : window.innerWidth-this.scrollbarwidth 
var docheight=(ie)? this.standardbody.clientHeight: window.innerHeight 
var docheightcomplete=(this.standardbody.offsetHeight>this.standardbody.scrollHeight)? this.standardbody.offsetHeight : this.standardbody.scrollHeight //Full scroll height of document 
var objheight=divobj.offsetHeight //height of div element 

divobj.style.top=Math.floor(parseInt(topposition))+"px" 

當前的Jquery我使用:

$(document).ready(function() { 
$(".projectThumb").click(function(e){ 
    $("#backgroundPopup").show(); 
    htmlName = $(this).find("img").attr("name"); 
    $("#data").load("/content/" + htmlName + ".html", null, function(){ 
     //Set Variables 
     var container = $(".container"); 
     var project = $(".project"); 
     var popupWidth = container.find(".project img:first").width(); 
     var popupHeight = container.find(".project img:first").height()+35; 
     var windowWidth = document.documentElement.clientWidth; 
     var windowHeight = document.documentElement.clientHeight; 

     //Set popup dimensions 
     container.css("width" , popupWidth); 
     container.css("height" , popupHeight); 

     //Set popup CSS 
     container.css({"position": "absolute", "background": "#000", "top": (windowHeight/2) - (popupHeight/2) + "px" "left": (windowWidth/2) - (popupWidth/2) + "px", "z-index": "2" }); 
     project.css({"width": (popupWidth), "height": (popupHeight) }); 

     }); 
    }); 
}); 

提前感謝!

回答

2

試試這個:

var x = ($(window).width()/2 - container.width()/2) + $(window).scrollLeft(); 
var y = ($(window).height()/2 - container.height()/2) + $(window).scrollTop(); 

然後用y爲你的左值的最高值,而x。

+0

這似乎工作,但我不得不改變container.width()popupWidth和container.height()popupHeight對應的變量。 有沒有辦法記錄彈出窗口是否大於屏幕,然後從頂部放置10PX? – antonanton

+0

您必須使用$(window).height()和$(window).width()獲取窗口的尺寸,然後根據容器的尺寸檢查這些尺寸。那麼做一個簡單的if else,或者使用給定的尺寸或者將y值改爲10。 –