Replace image by javascript

2019-07-29 03:30发布

I want to replace the gif file by javascript. I find the method below. Is there any way i can place the javascript tag before the img tag?

<img class="myImg" src="compman.gif" width="107" height="98">

<script>
    document.getElementsByClassName("myImg")[0].src = "hackanm.gif";
</script>

标签: image replace
2条回答
一夜七次
2楼-- · 2019-07-29 04:09

I believe OP's main concern was flash of the old image before it is replaced by JavaScript. I suggest you add a line of CSS to make your image element visibly hidden then do the swap + unhide with JavaScript.

<style>
    .myImg {visibility: hidden;}
</style>

<img class="myImg" src="compman.gif" width="107" height="98">

<script>
    var imgReplace = document.getElementsByClassName("myImg")[0];
    imgReplace.src = "hackanm.gif";
    imgReplace.style.visibility = "visible";
</script>
查看更多
Evening l夕情丶
3楼-- · 2019-07-29 04:17

A page can't be manipulated safely until the document is "ready." Using jquery's $(document).ready(), it Will wait until the page is loaded and ready to be manipulated before executing (no matter where it is on the page). Example:

<script>
    $(document).ready(function() {
        document.getElementsByClassName("myImg")[0].src = "hackanm.gif";
    });
</script>
<img class="myImg" src="compman.gif" width="107" height="98">

You could also then leverage selectors inside jquery (e.g. $(".class") where class is your class, or $("#id") where id is the id) and change the code to:

<script>
    $(document).ready(function() {
        $(".myImg").attr('src',"hackanm.gif");
    });
</script>
<img class="myImg" src="compman.gif" width="107" height="98">

And further you could even store it in a variable if you wanted to change it later on in javascript as well!

<script>
    $(document).ready(function() {
        var myImg = $(".myImg");
        var newImg = "hackanm.gif";
        myImg.attr('src', newImg);
    });
</script>
<img class="myImg" src="compman.gif" width="107" height="98">

Hope this helps you learn a few new tricks inside javascript! Happy coding!

More Info

查看更多
登录 后发表回答