2013-05-12 37 views
2

有人可以解释为什么这个代码不起作用。浏览器以值vspace =“0”响应。这意味着算术表达式不正确,但为什么?居中在页面中间的图像

<script type="text/javascript"> 

function resizeImage() 
{ 
var window_height = document.body.clientHeight 
var window_width = document.body.clientWidth 
var image_width = document.images[0].width 
var image_height = document.images[0].height 
var height_ratio = image_height/window_height 
var width_ratio = image_width/window_width 
var aspect_ratio = image_height/image_width 


if (height_ratio > width_ratio) 
{ 
    document.images[0].style.width = "auto"; 
    document.images[0].style.height = "100%"; 
} 
else 
{ 
    var new_vspace = Math.round((window_height - window_width*aspect_ratio)/ 2); 
    document.images[0].style.width = "100%"; 
    document.images[0].style.height = "auto"; 
    document.images[0].vspace="new_vspace"; 
} 
} 

</script> 
</head> 

<BODY bgcolor=#000000 onresize="resizeImage()"> 

<script> 
document.write('<center><img onload="resizeImage()" margin="0" border="0"  src="nweshow/picture-0011.jpg"/></center>') 
</script> 
</body> 
+4

难道你不能只设置图像的CSS属性? – 2013-05-12 04:34:08

+1

对这类事情使用CSS通常更快,更安全,并且在窗口调整大小时不会延迟。 – Greg 2013-05-12 04:40:15

+0

而你的代码适合我。你正在使用哪种浏览器? – Greg 2013-05-12 04:42:09

回答

0

我复制粘贴你的代码,并作出一个小的改变。

从这个

<center><img onload="resizeImage()" margin="0" border="0"  src="nweshow/picture-0011.jpg"/></center> 

对此

<div style="text-align: center"><img onload="resizeImage()" margin="0" border="0"  src="nweshow/picture-0011.jpg"/></div> 

其他然后,你的代码工作完全正常,图像大小调整和中心没有任何问题。

编辑:忘记提到我使用Flickr的图像进行检测,这里是链接:http://www.flickr.com/photos/[email protected]/8729551516/in/explore-2013-05-11

+0

要回答adamj提供的最后一个答案,text-align选项只能将图像水平放置在图像的中心位置顺便说一句,“堆栈溢出”添加注释的问题是您无法启动在按下之后,在注释中出现一个新行,这个键会立即添加[未完成]注释,所以我必须小心,这样会导致垂直居中图像的问题,以防i法师比我的代码= .54中定义的图片的高度:纵横比要大得多。所以屏幕底部有很多空白,但没有顶部。谢谢! – user2317959 2013-05-12 14:55:49

+0

试试'img {margin-left:auto;保证金右:自动;}' – Faizan 2013-05-13 16:52:59

0

问题通过加入这一行的条件的[如果一部分]解决“resizeImage()” :

document.images [0] .hspace = Math.floor((window_width - image_width/height_ratio)/ 2);

和添加此线为 “else” 部分:

document.images [0] = .vspace Math.floor((window_height - IMAGE_HEIGHT/width_ratio)/ 2);

非常感谢!

0

感谢您的建议,不要将vspace =的值放在引号中[与W3的引用相反],我将数学表达式直接写为[不带引号]的值并且不将其绑定到变量:add this line到“resizeImage()”的if部分:

document.images [0] .hspace = Math.floor((window_width - image_width/height_ratio)/ 2);

这个水平居中图像的情况下,高度= 100%

,并且还添加此线为 “else” 部分:

document.images [0] .vspace =数学。楼层((window_height - image_height/width_ratio)/ 2);

这种垂直居中图像的情况下,宽度调整为100%

这看起来很简单,不能由CSS来完成。

再次感谢您的帮助!