开发者

incorrect jQuery height

I have a page with two columns and try to make them the same height using jQuery... I have the following code

<script type="text/javascript"> 
$(document).ready(function() {
        var right_column_height = $("#right-column-wrapper").height()
        var content_height = $("#content-wrapper").height()
        console.log("content = " + content_height)

        if(right_column_height > content_height) $("#content-wrapper").css("height", right_column_height)
        else $("#right-column-wrapper").css("height", content_height)
})
</script> 

if right column is higher, its working correctly, but when when the content is higher, its acting weirdly... on one page the height is set as expected, on other page its not working at all... I added console logging to see whats happening and I see that the content height is not calculated in jQuery... but when I then enter the same code to console, I get a corret value... Can you suggest what's wrong in my code please...

See the demo at http://demo.romanpriryl.cz, the problematic page is http://beta.romanprikryl.cz/fotogalerie.htm, but working 开发者_运维问答correctly on http://beta.romanprikryl.cz/objednavky.htm


I've solved my issue when I put the code for resizing into the setTimeout function... a delay of 1 milisecond is enough, but still I dont understand why it's not working wihtout this... probably the page height is somehow calculated after the document is ready


Why are you using javascript to solve a problem that can easily fixed using CSS ?

See for instance this tutorial and this one as well


If either the #right-column-wrapper or the #content-wrapper elements have images without specified dimensions then jQuery will return the height of the container minus this image heights.

This happens because the images haven't loaded yet on $(document).ready() (this is also the most likely reason why a setTimeout is working).

To fix this, place the code where you want to get the element heights inside $(window).load().

e.g.

$(window).load(function() {
    var right_column_height = $("#right-column-wrapper").height()
    var content_height = $("#content-wrapper").height()
    console.log("content = " + content_height)

    if(right_column_height > content_height) $("#content-wrapper").css("height", right_column_height)
    else $("#right-column-wrapper").css("height", content_height)
});

Alternatively you can set the image width and height in HTML and jQuery will determine the correct height values for your elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜