赫謙小便籤

用jQuery的toggleClass來動態切換背景圖片

公司的某個開發中網站要實作一個登入按鈕會閃爍的功能,這個按鈕有兩張圖片(我知道CSS Sprite,但即便我有Compass我也懶得弄 …)來做相互切換。

原本的作法我是用一個index去當counter用,然後用setInterval的方式每秒用$(obj).css({background: 'url()'})的方式,但是這樣有一個問題就是會每次切換的時候都跟Server要圖片,這很麻煩真的 … 所以我就改成用指定class切換Background就好了。

application.css
1
2
3
4
5
6
7
  .login{
    background-image: url(/assets/common/login_2.png);

    &.star{
      background-image: url(/assets/common/login_1.png);
    }
  }

在登入的部份寫成這樣,然後Script寫成:

1
2
3
  setInterval ->
    $('.login').toggleClass('star');
  ,1000

是的,搞定。

Comments