jQuery height()函数返回不正确的值 [英] jQuery height() function returning inaccurate value

查看:131
本文介绍了jQuery height()函数返回不正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery测量两个div的高度(在加载文档后),然后使较短的div等于较高的div的高度.但是,其中一个div中有一个图像,似乎可以测量div的高度,就好像图像不存在一样(如果在加载所有内容后删除图像,则该高度是准确的).这是我的代码:

I'm using jQuery to measure the height of two divs (after document load) and then making the shorter div equal to the height of the taller div. However one of the div has an image in it, and it seems to be measure the height of the div as if the image isn't there (if I remove the image after everything has loaded, the height is accurate). Here is my code:

$(document).ready(function() {
    var rheight = $('#random').height();
    var qheight = $('#quote').height();
    if(rheight > qheight) $('#quote').height(rheight);
    else $('#random').height(qheight);
}

推荐答案

如果事先知道图像的高度,则可以设置图像标签的height属性.这将允许浏览器在加载图像之前以正确的高度渲染div,这意味着您的高度检查应能按预期进行.

If you know the height of the image in advance, you can set the image tag's height attribute. This will allow the browser to render the div at the correct height before the image loads, which means your height checks should work as expected.

根据其文档,使用jQuery挂载加载事件可能会出现问题.显然,该事件可以停止为已经存在于浏览器缓存中的图像触发".

Hooking the load event using jQuery can be problematic, according to its documentation. Apparently the event "can cease to fire for images that already live in the browser's cache".

这篇关于jQuery height()函数返回不正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆