jquery - 定位DIV

扫码查看

我想解构一些我在网站上为灯箱插件找到的JavaScript。

我很好奇是否有人可以帮助解码这段脚本?我想在我的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) });

        });
    });
});


提前致谢!

最佳答案

尝试这个:

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


然后,将y用作最高值,将x用作左侧值。

10-05 20:53
查看更多