簡體   English   中英

Javascript DOM onclick無法用於img src

[英]Javascript DOM onclick not working for img src

我不明白為什么不調用函數,或者為什么不更改背景圖像?

腳本標簽:

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

試試這個

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

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM