如何通过点击onclick将图像更改为不同的图像?

时间:2016-06-30 09:22:50

标签: javascript javascript-objects

如何通过onclick点击图像将图像更改为不同的图像?

#box{ height:200px; width:200px; background-color:gold; }
<body>
    <div id="box"></div>
    <script type="text/javascript">
        document.getElementById("box").onclick = function() {
            document.getElementById("box").style.display = ???? 
        }
    </script>
</body>

2 个答案:

答案 0 :(得分:0)

更新html元素的backgroundImage property in style property

document.getElementById("image1").onclick = function() {
   this.style.backgroundImage = 'url(img.jpg)'
}

#box {
  height: 200px;
  width: 200px;
  background-color: gold;
}
<div id="box"></div>
<script type="text/javascript">
  document.getElementById("image1").onclick = function() {
    this.style.backgroundImage = 'url(img.jpg)';
  }
</script>

答案 1 :(得分:0)

使用jQuery:

$('your_image_id_or_selector').click(function(){
   $(this).attr('src','new_image_url');
});