Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

css - jQuery toggle to change image

I have a list of divs with images in them:

<div class="wizard-img"><%= image_tag("sources/pix/nyt.png") %></div>
<div class="wizard-img"><%= image_tag("sources/pix/theguardian.png") %></div>

When a user clicks the div, I'd like it to change the image to x-on.png, when clicked again, it'll change to x-off.png, and when clicked a third time it should revert to x.png.

Is it possible to do this without manually specifying jQuery for every image change? Can I traverse the div and find the image name, and simply append the -off/-on to the image?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Perhaps CSS sprites would work for you?

That would save you from loading a separate image every time you click the image (button?), and you could solve your problem by adding and removing a css-class, e.g.:

$('.wizard-img').click(
    function() {
        if ($(this).hasClass('on')) {
            $(this).removeClass('on').addClass('off');
        } else if ($(this).hasClass('off')) {
            $(this).removeClass('off');
        } else {
            $(this).addClass('on');
        }
    }
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...