getting the height and width of a div after loadin

2019-08-03 18:00发布

问题:

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");

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();
        });

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?

回答1:

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();
    });
});


回答2:

Have you tried hiding the element by default, then before calling centerPopup(), show() it, but keep it's visibility hidden, then check for it's width() and height() to see if it's already got dimensions?