最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change CSS on click and back again on next click - Stack Overflow

programmeradmin1浏览0评论

I've looked around for an answer and nothing works for me. I want to be able to click a div and have the background change, then on the next click of the div I want it to change back again. The first part works, however I cannot figure out how to do the second part.

This is what works (using jQuery):

$(document).ready(function(){
$('.button').click(function() {
$('.icon').css("background-position", "0px 0px");
});
});

Any help would be appreciated, thanks.

I've looked around for an answer and nothing works for me. I want to be able to click a div and have the background change, then on the next click of the div I want it to change back again. The first part works, however I cannot figure out how to do the second part.

This is what works (using jQuery):

$(document).ready(function(){
$('.button').click(function() {
$('.icon').css("background-position", "0px 0px");
});
});

Any help would be appreciated, thanks.

Share Improve this question asked Apr 6, 2012 at 8:58 AnarcheiAnarchei 31 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Rather than use the .css method, I remend using .toggleClass and put the relevant css into a class:

$('.icon').toggleClass('myClass');

your class definition:

.myClass { background-position: 0px 0px };

The .toggleClass method will add the class if it's not already present or remove it if it is.

I agree with reendations to use .toggleClass(), but if you want to use .css() try this:

$(document).ready(function(){
  $('.icon').each(function(){
    $(this).data('default-bg-pos', $(this).css('background-position'));
    $(this).data('state', 0);
  });
  $('.button').click(function() {
    $('.icon').each(function(){
      if ($(this).data('state')) {
        $(this).data('state', 0);
        $(this).css('background-position', $(this).data('default-bg-pos'));
      } else {
        $(this).data('state', 1);
        $(this).css("background-position", "0px 0px");
      }
    });
  });
});

You should use a css class and toggle it.

.zero{
    background-position: "0px 0px";
}

$(document).ready(function(){

    $('.button').click(function() {

            $('.icon').toggleClass("zero")

    });
});
发布评论

评论列表(0)

  1. 暂无评论