我有这个功能:
function zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight){
var widthStep = (targetWidth - currentWidth) / 100;
var heightStep = (targetHeight - currentHeight) / 100;
var newWidth = Math.ceil( currentWidth + i * widthStep );
var newHeight = Math.ceil( currentHeight + i * heightStep );
i++;
var imageZ = document.getElementById(image);
imageZ.style.width = newWidth+"px";
imageZ.style.height = newHeight+"px";
while( i <= 100 )
t = setTimeout("zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight)",10);
}
这样调用:
zoomImage(0, "image1", 200, 150, 260, 195);
但由于某些原因,页面不会停止加载并最终崩溃。图像也不会变大。我在这里做错了什么?
最佳答案
我假设您在函数外初始化了 i
。当您进行递归调用时,i
将始终 传入。这是因为当您将字符串提供给 setTimeout
时,它会在全局范围内进行评估。
这意味着函数内部的i++
只影响局部的i
,而不影响全局的i
,所以i
从不递增不递增超过 1 + 全局值。
而是传递一个调用递归调用的匿名函数。这样你实际上传递了递增的 i
。
while( i <= 100 )
setTimeout(function() {
zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight);
},10);
当然,如评论中所述,while
在这里似乎不是正确的选择。
关于javascript - 尝试使用javascript创建一个函数来放大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8191038/