2017-08-31 134 views
0

我试图在图像变量中加载一张图片,并测试它是否是横向或纵向放入框架中。用户从下拉列表中选择URL。但是,下面的代码片段每隔一段时间就会给出0的宽度。我在做什么愚蠢的事情?在Javascript中获取图像变量的高度和宽度

 var Select_Picture = document.getElementById("ddlSelectPicture"); 
     var Client_Picture = document.getElementById("imgClientPicture"); 
     var Temp_Image = new Image(); 
     var Image_Height; 
     var Image_Width; 

     Temp_Image.src = Select_Picture.value; 

     // WAIT FOR PICTURE TO LOAD 
     while (Temp_Image.width < 1 || Temp_Image.height < 1) 
     { 
      Image_Width = Temp_Image.width; 
     } 
     Image_Height = Temp_Image.height; 

     alert(Image_Width + " " + Image_Height); 
+0

问题:这些元素是否在iFrame中? – Zak

+0

对于所有圣洁的爱,不要使用while循环。 Javascript是单线程的,当循环运行时你会阻塞所有的东西。相反,你可以这样做。 'Temp_Image.onload =函数(){/ * dostuff * /}; Temp_Image.src = Temp_Image.src;'或查找如何操作,在其上加载Q/A。 –

回答

1

您正试图在加载之前读取图像的高度和宽度。
onload将在Temp_Image完成加载时调用,因此图像将具有宽度和高度。

Temp_Image.onload = function() { 
    console.log(Temp_Image.width); 
} 
Temp_Image.src = Select_Picture.value; 
+0

这样做 - 不知道.onload或您可以使用它来执行内联函数。非常感谢您恢复我平时的疯狂。 :d – Wolfy

0

你可以直接得到这样的高度和宽度:

var height = document.getElementById("myImg").height; 
var width = document.getElementById("myImg").width; 
0

即使JavaScript是单线程的,浏览器不是。所以,当你尽最大努力让你的用户系统停下来时,你的浏览器仍然能够加载你的图像,现在需要将它的属性推送到javascript世界中供你访问。

您的while循环将继续跳入并阻碍浏览器尝试执行的所有JavaScript相关操作,因此即使在映像准备好之后,可能需要很多个事件循环才能实际填充属性widthheight对你的形象,他们可能不会在同一个循环更新。

所以你的测试会是这样的:(我们会假装这是一个100像素X 100像素)

// repeat this over and over and over 
if (Temp_Image.width < 1) /* true */ 
    Image_Width = Temp_Image.width /* 0 */ 

// until finally 
if (Temp_Image.width === 0 /* false */) 
    // okay we finally branched into right side of expression 
    if (Temp_Image.height < 1) /* ??? */ 
     // what now? 

那么,如果其真正的(意为高度尚未公布),它看起来像这样。

// keep repeating this over and over and over 
if (Temp_Image.width < 1) /* false */ 
    if (Temp_Image.height < 1) /* true */ 
     Image_Width = Temp_Image.width /* 100 */ 

// until finally 
if (Temp_Image.width < 1) /* false */ 
    if (Temp_Image.height < 1) /* false */ 
     break 
Image_Height = Temp_Image.height /* 100 */ 

// we've finally left the loop and the width is properly set 

那么如果它的假(意思是高度已经可用),它会看起来像这样。

if (Temp_Image.width < 1) /* false */ 
    break 
Image_Height = Temp_Image.height /* 100 */ 

// wait... hold on... we forgot to set the width 

您的宽度在循环的每次迭代遍地设置为0,但如果height属性已经可用,当你终于得到一个真实的宽度值,那么你在循环的前顶部突破存储在一个变量中。

无法保证首先设置哪个属性(宽度或高度),正如您的50/50结果清楚地表明的那样。

因此,如果这是为了学习循环,然后继续尝试让它自己正常工作。如果答案似乎对你不明显,可能是一个很好的练习。

但是,如果您实际上试图在浏览器中提供图片,请不要这么做!你正在阻止线程!停下来!

按照已经给出的倾听load事件的建议来代替循环。

相关问题