【问题标题】:how to replace an image with another onclick如何用另一个onclick替换图像
【发布时间】:2017-05-06 22:13:05
【问题描述】:

我有这两张图片的这些特点

#image1{
     position:absolute;
    left:29%;
    top:40%;
    background-image: url("../imgdrag/activity1.png");
    width:63px;
    height:38px;
}
#image2{
     position:absolute;
    left:29%;
    top:40%;
    background-image: url("../imgdrag/activity1red.png");
    width:63px;
    height:38px;
}

当我使用函数单击按钮时,如何将 image1 替换为 image2

【问题讨论】:

  • 有html代码吗?
  • 你尝试过什么 JavaScript/JQuery?

标签: javascript jquery


【解决方案1】:

使用 jQuery 切换状态的示例

$('.replace').click(function(){
  
  $('.image-holder').toggleClass('active');

})
#image1{
     position:absolute;
    left:29%;
    top:40%;
    background-image: url("../imgdrag/activity1.png");
    width:63px;
    height:38px;
    z-index: 2;
    background-color: blue;
}
#image2{
     position:absolute;
    left:29%;
    top:40%;
    background-image: url("../imgdrag/activity1red.png");
    width:63px;
    height:38px;
    z-index: 1;
    background-color: red;
}
.image-holder {
 position: relative;
}
.image-holder.active #image2{

   z-index: 3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="replace">Replace</button>

<div class="image-holder">

 <div id="image1"></div>
 <div id="image2"></div>

</div>

【讨论】:

    【解决方案2】:

    我建议将您的 css 更改为

    #image1 { 位置:绝对; 左:29%; 最高:40%; 背景图像:url(“../imgdrag/activity1.png”); 宽度:63px; 高度:38px; } #image1.active { 背景图像:url(“../imgdrag/activity1red.png”); }

    那么如果您使用的是 jquery,只需添加新的 'active' 类,并记得先检查它是否已经拥有它。

    $('button').on('click', function(e) { var img = $('#image1'); if (!img.hasClass('active')) { img.addClass('active'); } });

    【讨论】:

      【解决方案3】:
      // this with jQuery
      $("#button").click(function() {
          $('#image1').attr('id', '#image2');
      });
      

      function change(){
          document.getElementById('#image1').setAttribute('id', '#image2');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多