即使放在 $(window).load 内,我也会得到 $(image).width() == 0
我想调整比窗口大的图像大小,但当我尝试获取图像大小时,宽度和高度始终为 0。我在某处读到,这可能是因为图像不一定在 (document).ready 加载,因此图像函数应该在 (window).load 下加载,但它没有用。当涉及到 jquery 和 javascript 时,我是一个真正的新手,所以我可能做错了什么。
这就是我的 javascript 文件的样子:
//<!--
$(document).ready(function(){
...
});
$(window).load(function () {
$(".lightbox img").each(function() {
var width = $(this).width();
var max_width = $(window).width()-30;
var height = $(this).height();
var max_height = $(window).height()-30;
if(width > max_width || height > max_height) {
if(height > width) {
height = max_height;
width = Math.ceil(width / height * max_height);
} else {
width = max_width;
height = Math.ceil(height / width * max_width);
}
}
$(this).attr("width",width);
$(this).attr("height",height);
});
});
//-->
提前致谢。
I want to resize images that are bigger than the window, but I keep getting 0 width and height when I try to get the image size. I read somewhere that it could be because images aren't necessarily loaded at (document).ready so image functions should go under (window).load, but it's no use. I'm a real newbie when it comes to jquery and javascript so I could be doing something wrong.
This is how my javascript file looks:
//<!--
$(document).ready(function(){
...
});
$(window).load(function () {
$(".lightbox img").each(function() {
var width = $(this).width();
var max_width = $(window).width()-30;
var height = $(this).height();
var max_height = $(window).height()-30;
if(width > max_width || height > max_height) {
if(height > width) {
height = max_height;
width = Math.ceil(width / height * max_height);
} else {
width = max_width;
height = Math.ceil(height / width * max_width);
}
}
$(this).attr("width",width);
$(this).attr("height",height);
});
});
//-->
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看一下这个项目,它在图像加载时提供回调。
您可能无法获得尺寸的另一个原因是不可见元素(父元素或自身元素)。
Take a look at this project that provides a callback when images have loaded.
Another reason you could be getting no dimensions is an invisible element (parent or self).
尝试使用
$(this).css("width")
而不是attr
Try
$(this).css("width")
instead ofattr
当窗口加载时,图像还没有加载。在图像完全加载之前,JavaScript 无法获取图像的尺寸,在此之前,您得到的计算值为零。
记住这一点,重复循环可能会有所帮助。 (警告:尚未测试)
不过,请注意无限循环。
When the window loads, the images haven't necessarily loaded yet. JavaScript can't get an image's dimensions until is has completely loaded, and until then, you get a computed value of zero.
Bearing this in mind, a repeating loop might help. (Warning: haven't tested)
Watch out for infinite loops, though.