图像调整大小NaN错误

Image Resize NaN Error

本文关键字:NaN 错误 调整 图像      更新时间:2023-09-26

我从我的一个函数中得到NaN。经过一番研究,我发现答案不是一个数字,但我认为这肯定是不可能的。我只处理数字,我正在四舍五入的答案。

 function resize(iid, eid) {
//Get the ID of the elements (ele being the container that the image is in and img being the image its self)
     var img = document.getElementById('img');
     var ele = document.getElementById('contaner');
//makes the var needed
     var currentwidth = ele.clientWidth;
     var currentheight = ele.clientHeight;
     var naturalwidth = img.naturalHeight;
     var naturalheight = img.naturalWidth;
     var newheight = naturalheight;
     var newwidth = naturalwidth;
     var x;
     //runs a loop that should size the image
        while (newheight > currentheight && newwidth > currentwidth){
            x = x + 1;
            newheight = naturalheight / x;
            newwidth = naturalwidth / x;
        }
     newheight = Math.round(newheight);
     newwidth = Math.round(newwidth);
     //alerts out the  answers
     alert(newheight);
     alert(newwidth)
}
#contaner {
    height: 450px;
    width: 90%;
    margin: 5% auto;
    position: relative;
}
#img {
    height: 450px;
    width: 90%;
}
<div id="contaner">
                <img src = "..'..'Resorces'Images'SlideShow'img1.jpg" style="width:652px;height:489px;" id="img"/>
                <div id="left_holder"><img onClick="slide(-1)" src="..'..'Resorces'Images'arrow_left.png" class="left"/></div>
                <div id="right_holder"><img onClick="slide(+1)" src="..'..'Resorces'Images'arrow_right.png" class="right"/></div>
            </div>

你有:

var x;

当你这样做的时候:

x = x + 1;

xundefined,它被强制转换为字符串,然后与1连接。所以:

x = 'undefined1';

x用于除法时,它返回NaN。

解决方案:修改x声明:

var x = 0;

NaN由这行代码完成:

var x;
while (newheight > currentheight && newwidth > currentwidth) {
     x = x + 1; //<- Here x is undefined
}