使用jQuery从外部源将信息加载到div后,获取div的高度和宽度

使用jQuery从外部源将信息加载到div后,获取div的高度和宽度

问题描述:

我见过与此类似的问题,但没有找到适合我的情况的答案.我使用jQuery创建了一个简单的模式弹出插件,其运行方式如下: $('#popup').popupElement("http://www.example.com #somediv");

I've seen questions similar to this but haven't found an answer for my situation. I've created a simple modal popup plugin using jQuery that runs like this: $('#popup').popupElement("http://www.example.com #somediv");

单击选择器#popup时,它将从另一个网站加载div.点击功能如下所示:

It loads divs from another website when the selector #popup is clicked. The click function looks like this:

            $(thisObj).click(function(e){
            e.preventDefault();
            $("#popupDiv").load(div);
            centerPopup();
            loadPopup();
        });

问题是当将外部div加载到popupDiv中时,popupDiv的高度和宽度为0,因此centerPopup()无法将其正确居中.单击#popup链接几次后,popupDiv的尺寸会自行修复.有没有办法确保在调用centerPopup()之前将popupDiv设置为正确的尺寸?

The problem is when it loads the external div into the popupDiv, the popupDiv's height and width are 0, so centerPopup() can't center it right. After clicking the #popup link a few times the popupDiv's dimensions fix themselves. Is there a way to ensure the popupDiv gets set to the right dimensions before centerPopup() is called?

尝试将对centerPopup()loadPopup()的调用放在load()的回调函数中.在尝试显示弹出窗口之前,这将确保内容在DOM中,这意味着高度和宽度应可访问.试试这个:

Try placing the calls to centerPopup() and loadPopup() in the callback function of the load(). This will ensure that the content is in the DOM before you try and show the popup, which means that the height and width should be accessible. Try this:

$(thisObj).click(function(e){
    e.preventDefault();
    $("#popupDiv").load(div, function() {
        centerPopup();
        loadPopup();
    });
});