JavaScript change img src attribute without jQuery

前端 未结 6 1825
礼貌的吻别
礼貌的吻别 2020-12-06 01:44

How to change the src attribute of a HTMLImageElement in JavaScript?

I need help to convert logo.attr(\'src\',\'img/rm2.png\')

6条回答
  •  时光说笑
    2020-12-06 02:24

    You mean you want to use pure javascript?

    This should do it:

    var logo = document.getElementById('rm');
    logo.src = "img/rm2.png";
    

    So your function should look like :

    window.onresize = window.onload = function () {
        if (window.innerWidth > 1536) {
          var logo = document.getElementById('rm');
          logo.src = "img/rm2.png";
        }
    };
    

    Note: You could also use element.setAttribute. BUT, see this post for more:
    When to use setAttribute vs .attribute= in JavaScript?

提交回复
热议问题