javascript - 尝试使用javascript创建一个函数来放大图像

标签 javascript image function

我有这个功能:

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/

相关文章:

c++ - 我的功能中缺少什么吗?

javascript - 在对话框中显示值

c++ - 警告 : control reaches end of non-void function in recursive function

javascript - 播放 HLS 文件时 JWPlayer controlbar 错误

c# - 通过取色排除图像的一部分

python - PyAutoGui 无法在全屏程序中定位图像

jquery - 如果图像没有 css 类,jQuery 可以将它添加到图像吗?

android - 如何在键盘上的xml中为功能键设置不同的背景?

javascript - 使用 navigator.mediaDevices.getUserMedia 录制浏览器音频

javascript - 如何制作 `text + line-break + link` 以在 Whatsapp 上分享?