使用jquery单击图像后,将图像更改为另一个图像

时间:2013-09-08 01:18:20

标签: javascript jquery css toggle

这是我到目前为止的第一个问题,因为我在使用论坛之前总是进行研究,但我不能让它发挥作用。

我有一个用作切换动画按钮的图像(button.png),我希望该图像在点击另一个图像(button2.png)后更改,一旦你点击第二个图像,它就会改变再次到第一张图片,我有:

<script type="text/javascript">
$(document).ready(function() {

  // when click on the tag with id="btn"
  $('#btn').click(function() {
      // change the state of the "#idd"
    $('#idd').toggle(800, function() {
      // change the button text according to the state of the "#idd" 
      if ($('#idd').is(':visible')) {
        $('#btn').attr('images/button2.png', this.href); // Show Less.. button
              } else {
        $('#btn').attr('images/button.png', this.href); //Learn More.. button

      }
    });
  });
});
</script>

和我的Html:

<div id="idd" style="display:none;">

- Here my hidden content -

</div>

<!-- Button -->
<img src="images/button.png" style="cursor: pointer;" id="btn">

我做错了什么?请帮忙:(

4 个答案:

答案 0 :(得分:3)

检查.attr的语法。它应该像

$('#btn').attr('src', 'your image src'); 

功能参考:http://api.jquery.com/attr/

答案 1 :(得分:3)

要更改src的值,请使用'attr',如下所示:

$('#btn').attr('src', 'images/button2.png');

这是DEMO

<强> HTML

<div id="idd" class='display-none'>

- Here my hidden content -

</div>

<!-- Button -->
<img src="http://placekitten.com/40/40" id="btn">

<强> CSS

.display-none {
    display:none;
}

<强>的jQuery

var btn = $('#btn');
var idd = $('#idd');

btn.click(function() {  
   idd.toggle(800, function() {
      // change the button text according to the state of the "#idd" 
      if (idd.hasClass('display-none')) {
        btn.attr('src', 'http://placekitten.com/50/50'); 
          idd.removeClass('display-none');
              } else {
        btn.attr('src', 'http://placekitten.com/40/40');
          idd.addClass('display-none');
       }
    });
  });

答案 2 :(得分:1)

采取一个划分,例如#play-pause-button等,即#play-pause。现在将你的图像放在内部分区的src中,在内部分区的外部分割源点击将改变.. 这是我正在努力的simillar例子。希望对你有所帮助。

$('#play-pause-button').click(function () {
            // $('#play-pause-button').play();
            if ($("#media-video").get(0).paused) {
                $("#media-video").get(0).play();
                $("#play-pause").attr('src', "Image1 path");
            }
            else {
                $("#media-video").get(0).pause();
                $("#play-pause").attr('src', "Image2 path");
            }
        });

答案 3 :(得分:0)

您应该使用css将图像与“按钮”和css类相关联,以确定要显示的内容。

然后,您可以使用Jquery的ToggleClass()来添加/删除该类。您可以使用同一个班级来显示/隐藏隐藏的内容。

标记

<div id="idd">
   - Here my hidden content -
</div>
<div id="btn">Click Me</div>

CSS

#idd.off {
    display:none;
}
#btn {
    border:1px solid #666;
    width:100px; height:100px;
    background:#fff url(images/button.png) no-repeat 0 0;  // Show Less.. button
}
#btn.off {
    background:#fff url(images/button2.png) no-repeat 0 0; //Learn More.. button
}

jquery的

$('#btn').click(function(){
    $('#idd').toggleClass('off');
    $('#btn').toggleClass('off');
});
相关问题