【问题标题】:Centering an image in the middle of the page在页面中间居中图像
【发布时间】:2013-05-06 10:25:20
【问题描述】:

谁能解释一下为什么这段代码不起作用。浏览器以值 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>

【问题讨论】:

  • 不能只设置图片的CSS属性吗?
  • 对这类事情使用 CSS 通常更快、更安全,并且在调整窗口大小时不会滞后。
  • 你的代码对我有用。你用的是哪个浏览器?
  • 不要使用 JS,而是这样做:css-tricks.com/perfect-full-page-background-image
  • document.images[0].vspace="new_vspace";new_vspace写在“”之间正常吗?不是 var 吗?

标签: javascript html image centering


【解决方案1】:

感谢您的建议,不要将 vspace= 的值放在引号内 [与 W3 的参考相反] 我将数学表达式直接写为其值 [不带引号] 并且不将其绑定到变量:将此行添加到"resizeImage()" 的 if 部分:

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

如果 height= 100%,这会使图像水平居中

并将这一行添加到“else”部分:

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

如果宽度调整为 100%,这会使图像垂直居中

这看起来很简单,CSS 做不到。

再次感谢您的帮助!!

【讨论】:

    【解决方案2】:

    通过将此行添加到“resizeImage()”的条件 [if-part] 来解决问题:

    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);

    非常感谢!

    【讨论】:

      【解决方案3】:

      我已经按原样复制粘贴了您的代码并做了一个小改动。

      从此

      <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/23397895@N08/8729551516/in/explore-2013-05-11

      【讨论】:

      • 回答adamj的最后一个答案。 text-align 选项仅将图像水平居中。顺便说一句,“堆栈溢出”添加 cmets 的问题是,您无法通过按 在注释中开始新行,因为此键会立即添加 [未完成] 注释,所以我必须小心。这留下了图像垂直居中的问题,以防图像的宽度远大于高度:我的代码中定义的相关图片的纵横比 = .54。所以屏幕底部有很多空白,但顶部没有。谢谢!
      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 2018-02-05
      • 2013-10-22
      • 2017-09-29
      • 2013-02-19
      • 1970-01-01
      • 2012-04-27
      • 2015-04-27
      相关资源
      最近更新 更多