Javascript DOM onclick无法用于img src

时间:2019-02-09 02:45:41

标签: javascript

我不明白为什么不调用函数,或者为什么不更改背景图像?

脚本标签:

<script type="text/javascript" >
    function start() 
    {
        document.body.style.backgroundImage = "url('sothback.png')";
        document.body.style.backgroundSize = "100%";
        document.body.style.backgroundRepeat = "repeat-y"; 
    }

    window.onload = start;

    function cartman() 
    {
        document.getElementById("image").style.src = "cartman.png";
    }


    function kenny() 
    {
        document.getElementById("image").style.src = "kenny.png";
    }

</script>

正文:

<body>
    <div style="width: 100%; height: 700px;">
        <button onclick="kenny()">Kenny</button>
        <button onclick="cartman()">cartman</button>
        <div style="height: 400px;"></div>
        <center><img src="kenny.png" alt="img" id="image" ></center>
    </div>
</body>

2 个答案:

答案 0 :(得分:0)

尝试一下

 function cartman() {
   document.getElementById("image").setAttribute('src','cartman.png');
 }
 function kenny() {
   document.getElementById("image").setAttribute('src','kenny.png');
 }

答案 1 :(得分:0)

    function start() 
    {
        document.body.style.backgroundImage = "url('sothback.png')";
        document.body.style.backgroundSize = "100%";
        document.body.style.backgroundRepeat = "repeat-y"; 
    }

    window.onload = start;

    function cartman() 
    {
        document.getElementById("image").setAttribute('src',"cartman.png");
document.getElementById("image").setAttribute('alt',"Image of cartman");
    }


    function kenny() 
    {
        document.getElementById("image").setAttribute('src',"kenny.png");
document.getElementById("image").setAttribute('alt',"Image of kenny");
    }

</script>
    <div style="width: 100%; height: 700px;">
        <button onclick="kenny()">Kenny</button>
        <button onclick="cartman()">cartman</button>
        <div style="height: 400px;"></div>
        <center><img src="kenny.png" alt="img" id="image" ></center>
    </div>

style.src更新为setAttribute。 还可以考虑设置alt标签和title来实现辅助功能和屏幕阅读器。