Javascript:图片对象 - > HTML图像元素

时间:2014-01-06 16:23:24

标签: javascript html

代码将图像预加载到图像对象中,然后(假设)将其设置为HTML上的图像元素src:

<!DOCTYPE html>
<html>
  <head>
    <script language="javascript">
        window.onload = function () {
            var oImage = new Image();
            oImage.onload = function () {
                document.getElementById('myImage').src = oImage;
                alert('done');
            };
            oImage.src = 'image1.jpg';
        }
    </script>
  </head>
  <body>
    <img id="myImage" src="" />
  </body>
</html>

为什么它不起作用?

1 个答案:

答案 0 :(得分:6)

尝试

<!DOCTYPE html>
<html>

<head>

    <script language="javascript">
        window.onload = function () {

            var oImage = new Image();

            oImage.onload = function () {
                document.getElementById('myImage').src = oImage.src;
                alert('done');

            };

            oImage.src = 'image1.jpg';
        };
    </script>

</head>

<body>
    <img id="myImage" src="" />
</body>

</html>

您无法为图片设置 src ,您必须将其设置为图片的 src。(PS:最后添加分号并更改{{ 1}}到.src = oImage

<强> DEMO