2015-10-18 36 views
0

此代码在运行时应调整图像适合容器的高度和宽度。Javascript函数未给出图像的预期结果

这是从代码的输出(来自警报):

2488:图像自然高度

3264:图像自然宽度

450:容器高度

1063:该集装箱宽度

612:新高度

844:新的宽度

4:

新宽度:544

的时候,它被划分去输出

**应该把它的6倍,提供的结果数

新的高度:414 **

我几乎可以肯定,这个问题是在Java脚本:

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 naturalheight = img.naturalHeight; 
 
    var naturalwidth = img.naturalWidth; 
 
    var newheight = naturalheight; 
 
    var newwidth = naturalwidth; 
 
    var x = 0; 
 
    //runs a loop that should size the image 
 
     while (newheight > currentheight && newwidth > currentwidth){ 
 
      x = x + 1; 
 
      newheight = naturalheight/x; 
 
      newwidth = naturalwidth/x; 
 
     } 
 
    newheight = Math.ceil(newheight); 
 
    newwidth = Math.ceil(newwidth); 
 
    //alerts out the answers 
 
    alert(naturalheight); 
 
    alert(naturalwidth); 
 
    alert(currentheight); 
 
    alert(currentwidth); 
 
    alert(newheight); 
 
    alert(newwidth); 
 
    alert(x); 
 
}
#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>

回答

0

的问题是这一行:

while (newheight > currentheight && newwidth > currentwidth) 

它停止尽快要么容器,在那里,因为它似乎像你想内宽度或高度配合适合容器的边界。更改为||,您将获得六次迭代:

while (newheight > currentheight || newwidth > currentwidth) 
+0

谢谢sooo much! – adbadb25

相关问题