JavaScript仅在重新加载页面时有效

时间:2010-01-07 16:55:57

标签: javascript image reload

我有一个相当简单的页面,在弹出窗口中显示图像。 onLoad事件只需获取查询字符串,使用该值填充图像标记,然后调整图像和窗口的大小以匹配。

出于某种原因,这仅适用于重新加载/刷新页面的情况。或者,一旦图像显示一次,即使关闭了缓存,它也将从此开始工作。但是,无论何时第一次查看图像,页面都会显示为空白而没有错误。

有什么建议吗?

由于

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Image Zoom</title>
    <meta http-equiv="Pragma" content="no-cache" />
    <script type="text/javascript">
        function getImage() {
            //get the query string (everything after the ?)
            var filename = window.location.search.substring(1);
            //find the image control
            var imageWorking = document.getElementById('dynamicImage');
            //assign the image source
            imageWorking.src = '../Images/' + filename;
            //create an image variable
            var newImg = new Image();
            //assign the source to match the page image
            newImg.src = imageWorking.src;
            //get the width and height
            var width = newImg.width;
            var height = newImg.height;
            //set the page image width and height to match the disk image
            imageWorking.width = width;
            imageWorking.height = height;
            //set the window to be just larger than the image
            window.resizeTo(width + 50,height + 50);
        }
    </script>
</head>
<body onload="getImage();">
    <img src="images/spacer.gif" id="dynamicImage" alt="Image Zoom" width="1" height="1" />
</body>
</html>

使用以下函数调用页面:

function imageZoom(imageName)
{
    window.open('ImageZoom.htm?' + imageName + '','imageZoom','width=400,height=400,menubar=no,toobar=no,scrollbars=yes,resizable=yes');
}

3 个答案:

答案 0 :(得分:1)

在页面加载期间使用JavaScript动态编写IMG标记,并在onload上调整窗口大小:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Image Zoom</title>
  <meta http-equiv="Pragma" content="no-cache" />
  <script type="text/javascript">
    function sizeWindow() {

      //find the image control
      var img = document.getElementById('dynamicImage');

      //set the window to be just larger than the image
      window.resizeTo(img.width + 50, img.height + 50);
    }
  </script>
</head>
<body onload="sizeWindow();">
  <script type="text/javascript">
    var filename = window.location.search.substring(1);
    document.write("<img src='../Images/" + filename + "' id='dynamicImage' alt='Image Zoom' />");
  </script>
</body>
</html>

答案 1 :(得分:0)

您需要先将<img>的SRC设置为某个值。如果您不想显示任何内容,只需使用1x1像素透明GIF。

答案 2 :(得分:0)

您是否尝试将getImage函数绑定到窗口的onload事件而不是绑定到body的onload?