chrome中使用jquery的图像高度问题
$('img').height()
在 Chrome 中返回 0
,但在 IE 和 Firefox 中返回实际高度。
在 Chrome 中获取图像高度的实际方法是什么?
$('img').height()
returns 0
in chrome, but it returns the actual height in IE and firefox.
Whats the actual method to get the height of the image in chrome?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
正如 Josh 提到的,如果图像尚未完全加载,jQuery 将不知道尺寸是多少。尝试这样的操作,以确保您仅在图像完全加载后尝试访问其尺寸:
As Josh mentioned, if the image has not fully loaded yet, jQuery won't know what the dimensions are yet. Try something like this to ensure you're only attempting to access it's dimensions after the image has been completely loaded:
我的假设是在图像加载完成之前调用该函数。您能否尝试延迟该函数以查看是否确实如此?如果是这种情况,您可以在运行该函数之前使用计时器进行作弊。
检测图像何时加载有点复杂。 看看这个脚本的一些想法 - 也许它会为你工作。
My assumption is that this function is being called before the image is finished loading. Can you try putting a delay on the function to see if this is actually the case? If this is the case, you can cheat by using a timer before running the function.
It is a bit more complicated to detect when an image has been loaded. Have a look at this script for some ideas -- maybe it would work for you.
您可能需要预加载图像并设置回调函数:
Preloading the image and setting up a callback function might be what you're looking for:
我使用的一个稍微丑陋但有效的修复方法是使用后端语言(在我的例子中是 php)来获取高度并将其设置在图像上,然后再将其发送到浏览器。
它很丑陋,但是简单快捷
A slightly ugly but effective fix that I used was use a backend language, in my case php, to get the height and set it on the image before sending it to the browser.
it's ugly, but simple and quick
尝试使用图像预加载器,这是我写的获取另一个问题的答案。
Try using an image pre-loader, here's one I wrote for an answer to another question.
刚刚做了一些实验,我发现
返回 0 - 但是如果你只使用普通的旧 JS,
我会得到正确的图像高度。
Having just done some experiments with this I've found that
Returns 0 - however if you just use plain old JS
I get the correct image height.
刚刚遇到了同样的问题:通过 CSS 或 HTML 预先设置宽度和高度。
Just had the same issue: set the width and height beforehand via CSS or HTML.