Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我得到$(image).width()==0,即使放在$(window.load)中也是如此_Javascript_Jquery_Image_Resize_Window - Fatal编程技术网

Javascript 我得到$(image).width()==0,即使放在$(window.load)中也是如此

Javascript 我得到$(image).width()==0,即使放在$(window.load)中也是如此,javascript,jquery,image,resize,window,Javascript,Jquery,Image,Resize,Window,我想调整比窗口大的图像的大小,但是当我尝试获得图像大小时,我的宽度和高度一直为0。我在某个地方读到,这可能是因为图像不一定在(document.ready)加载,所以图像函数应该在(window.load)下加载,但这没有用。对于jquery和javascript,我是一个真正的新手,所以我可能做错了什么 以下是我的javascript文件的外观: //<!-- $(document).ready(function(){ ... }); $(window).load(funct

我想调整比窗口大的图像的大小,但是当我尝试获得图像大小时,我的宽度和高度一直为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);

    });
});

//-->
//
提前感谢。

尝试
$(this).css(“width”)
而不是
attr

查看在加载图像时提供回调的


另一个没有尺寸标注的原因是一个不可见的元素(父元素或自元素)。

当窗口加载时,图像不一定已经加载。在完全加载之前,JavaScript无法获取图像的维度,在此之前,计算值为零

记住这一点,重复循环可能会有所帮助。(警告:尚未测试)


但是要注意无限循环。

这是页面顶部的脚本标记吗?这实际上不会停止图像加载吗?我真的不建议像这样使用
while
循环。为什么不使用
$(this).on(“加载”,…)?图像还有一个
load
事件。是的,它是一个不可见的元素(在事件发生后可见)。我没有想到这一点,尽管这很有道理。现在我得到的大小后,该元素是可见的,它的工作,谢谢!
var width = 0;
while (!width) {
    width = $(this).width();
}