14
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryのanimate()でbackground-colorを変える

Posted at

jQueryを書いていて、背景をアニメーションで変化させようと思ったらハマってしまったので

そもそもanimate()とは

animate()とは独自のアニメーションを作成する関数です
animate(params, [duration], [easing], [callback])
paramsはstyle、durationにはアニメーションの時間、easingには変化方法、callbackにはアニメーション終了時に実行する関数のポインタを渡すことができます。

$(".hoge").click(function(){
  $(this).animate({ 
    width: "50%",
    opacity: 0.5
  }, 1500, 'linear', func() );
});

こうするとhogeクラスがクリックされた時に、1500msかけてlinear(等速)でwidthを50%、opacityを0.5に変化させ、終了後にfunc()を呼び出すという形になります。

animate()は数値型の値しか対応していない

私がなんでハマったかというと、animate()のparamsに指定するものは、数値型(100,50%,25pxとか)しか対応していないようで、background-colorの値である#99ccffといった指定はできないようになっています、ちゃんとリファレンスに書いてましたね…
ちなみにbackground-colorのようにハイフンが入っているものはbackgroundColorのようにキャメルケースで記述します。

/* これはダメ */
$(".hoge").click(function(){
  $(this).animate({ 
    backgroundColor: "#99ccff"
  }, 1500, 'linear', func() );
});

解決策

リファレンスにも書いてあるようにjQuery.Colorというプラグインを使えば解決するようですが、今回はjQuery UIを使用しました。
これはjQuery公式のUI用のプラグインです、今回はColor Animationの機能を使います。
導入方法は簡単、ここにアクセスして、jQuery UIのスニペットをコピーして貼り付けます。

<head>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

</head>

普通のjQueryの後に読み込む点に注意してください、これだけでさっきのjQueryが動きます。


公式リファレンスはちゃんと読まないとダメですね…

14
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?