此代码在运行时应调整图像的高度和宽度以适合容器。
这是代码的输出(来自警报):
2488:图像自然高度
3264:图像自然宽度
450:容器高度
1063:容器宽度
612:新高度
844:新宽度
4:分割到输出的次数
**它应该分为6次以提供结果:
新宽度:544
新身高:414 **
我几乎可以肯定问题出现在Java Script中:
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 :(得分:0)
问题在于这一行:
while (newheight > currentheight && newwidth > currentwidth)
只要 宽度或高度适合容器内部就会停止,因为您似乎希望两者都适合容器的范围。更改为||
,您将获得六次迭代:
while (newheight > currentheight || newwidth > currentwidth)