开发者

Toggle src-attribute on image

Is there a way to toggle the src attribute of an image betwee开发者_开发问答n two values when an anchor is clicked?

Like this:

$('a#some-anchor').click(function() {
// code here that toggles between two image src's e.g. "images/some-image1.jpg" and "images/some-image2.jpg"
});


$("img").bind("click", function() {
  var src = ($(this).attr("src") === "img1_on.jpg")
                ? "img2_on.jpg" 
                : "img1_on.jpg";
  $(this).attr("src", src);
});

Taken from here:

Changing the image source using jQuery


Using internal data() function could work:

$('a#some-anchor').click(function() {
  var img = $(this);
  if ( img.data('active') ) {
    img.attr('src', 'images/some-image1.jpg');
    img.data('active', false);
  } else {
    img.attr('src', 'images/some-image2.jpg');
    img.data('active', true);
  }
});


Don't know where you image are but:

$('a#some-anchor').click(function() {
    var img = $('selector');

    if (img.attr('src').match(/image1/)) {
        img.attr('src', 'images/some-image2.jpg');
    } else {
        img.attr('src', 'images/some-image1.jpg');
    }
});


$('a#some-anchor').click(function() {
    var img = $('#yourIMG');

    var img1 = "images/some-image1.jpg";
    var img2 = "images/some-image2.jpg";

    img.attr('src', img.attr('src') == img1 ? img2 : img1);
});


Checkout this snippet:

var plus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png';
var minus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5802-200.png';

$('#magic-toggle').click(function() {
  if ($('.fun-img').attr('src') === plus) {
    $('.fun-img').attr('src', minus);
  } else {
    $('.fun-img').attr('src', plus)
  }
})
.fun-img {
  width: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png" class="fun-img" id="magic-toggle">

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜