即使JavaScript是单线程的,浏览器不是。所以,当你尽最大努力让你的用户系统停下来时,你的浏览器仍然能够加载你的图像,现在需要将它的属性推送到javascript世界中供你访问。
您的while循环将继续跳入并阻碍浏览器尝试执行的所有JavaScript相关操作,因此即使在映像准备好之后,可能需要很多个事件循环才能实际填充属性width
和height
对你的形象,他们可能不会在同一个循环更新。
所以你的测试会是这样的:(我们会假装这是一个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
事件的建议来代替循环。
问题:这些元素是否在iFrame中? – Zak
对于所有圣洁的爱,不要使用while循环。 Javascript是单线程的,当循环运行时你会阻塞所有的东西。相反,你可以这样做。 'Temp_Image.onload =函数(){/ * dostuff * /}; Temp_Image.src = Temp_Image.src;'或查找如何操作,在其上加载Q/A。 –