简体   繁体   中英

JavaScript trying to change image

There are four files at the same folder directory

- 1.jpg 
- 2.jpg 
- index.html 
- 1.js

I am hoping to write the code so it will load 1.jpg at first, but it will load 2.jpg next

The JavaScript is

var img = new Image();   // Create new img element
img.src = '2.jpg';


var getElementIMG = document.getElementById("imageid");
getElementIMG.src = img.src;

And the HTML is

<img id="imageid" src="1.jpg">

but when the page finishes loading it still displays 1.jpg

If your Javascript is on the header you need to specify when do you want the image to be replaced, which is when it exists.

After the window has been loaded:

window.onload = function () {
    document.getElementById("imageid").src = "2.jpg";
}

Demo: http://jsfiddle.net/5a6Jx/2/

Or you can just stick the script at the end of the page:

<img id="imageid" src="1.jpg" />

<script type="text/javascript">
    document.getElementById("imageid").src = "2.jpg";
</script>

On both ways your image will be there already, so you can manipulate it.

<head> <script type="text/javascript" src="1.js"></script> </head>

The script is loaded in the head and executed immediately. There is no element '#imageid', so document.getElementById returns null . An error is probably thrown on the getElementIMG.src = img.src; line. If something doesn't work, one of the first things you should do is check for errors in the debugger/console. (F12 in most browsers.)
Later on the page, the browser sees an image. It displays it.

What you want to do is load the script after the image. If you put it at the end of the page, the <img> will be seen by the browser, and only after that, its src will be changed.

Try this:

<!doctype html>
    <html>
       <body>
          <img id="imageid" src="1.jpg">
          <script>
              var getElementIMG = document.getElementById("imageid");
              getElementIMG.src = '2.jpg';
          </script>
       </body>
    </html>

You will have to make your move when the document and your image are both loaded.

window.onload = function () {
    var img = new Image();
    img.src = '2.jpg';

    img.onload = function() {
        var getElementIMG = document.getElementById("imageid");
        getElementIMG.src = img.src;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM