最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: image object -> HTML image element - Stack Overflow

programmeradmin2浏览0评论

The code preloads an image into an image object and then (supposed to) set it to the image element src on HTML:

<!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>

Why it doesn't work?

The code preloads an image into an image object and then (supposed to) set it to the image element src on HTML:

<!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>

Why it doesn't work?

Share Improve this question edited Jan 6, 2014 at 16:34 Sachin Jain 21.9k34 gold badges110 silver badges176 bronze badges asked Jan 6, 2014 at 16:23 AzevedoAzevedo 2,1897 gold badges35 silver badges53 bronze badges 2
  • Where is your 'image1.jpg' located? Is it in the same folder as your HTML file? – Marvin Brouwer Commented Jan 6, 2014 at 16:27
  • yes. I'm testing it locally. – Azevedo Commented Jan 6, 2014 at 16:29
Add a ment  | 

1 Answer 1

Reset to default 6

Try

<!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>

You can't set a src to an image, you have to set it to the image's src. (PS: Added semicolon at the end and changed .src = oImage to .src = oImage.src)

DEMO

发布评论

评论列表(0)

  1. 暂无评论