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

Trying to make a function with javascript to enlarge an image

本文关键字:一个 函数 图像 放大 javascript 创建      更新时间:2023-09-26

我有这个函数:

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在这里似乎不是正确的选择。