if の使い方については、特に悪いことはありません。問題ないです。
繰り返し同じコードを書いているのは、DRYではないので、以下のように書いてはいかが?
html
1<!DOCTYPE HTML>
2<html lang="ja-JP">
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 <style type="text/css">
7 .contents {
8 border: 1px solid #CCC;
9 height: 600px;
10 }
11 .animate {
12 background: red;
13 }
14 </style>
15 </head>
16 <body>
17 <div>
18
19 <div class="contents aaa"></div>
20 <div class="contents bbb"></div>
21 <div class="contents ccc"></div>
22
23 </div>
24 <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
25 <script type="text/javascript">
26 $(function () {
27 $(window).scroll(function () {
28 var selectors = $('.aaa, .bbb, .ccc');
29 var scroll = $(window).scrollTop();
30 selectors.each(function () {
31 var position = $(this).offset().top - $(window).height();
32 if (position < scroll) {
33 $(this).addClass("animate");
34 }
35 });
36 });
37 });
38 </script>
39 </body>
40</html>
もっとDRYに
html
1<!DOCTYPE HTML>
2<html lang="ja-JP">
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 <style type="text/css">
7 .contents {
8 border: 1px solid #CCC;
9 height: 600px;
10 }
11 .animate {
12 background: red;
13 }
14 </style>
15 </head>
16 <body>
17 <div>
18
19 <div class="contents"></div>
20 <div class="contents"></div>
21 <div class="contents"></div>
22
23 </div>
24 <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
25 <script type="text/javascript">
26 $(function () {
27 $(window).scroll(function () {
28 var selectors = $('.contents');
29 var scroll = $(window).scrollTop();
30 selectors.each(function () {
31 var position = $(this).offset().top - $(window).height();
32 if (position < scroll) {
33 $(this).addClass("animate");
34 }
35 });
36 });
37 });
38 </script>
39 </body>
40</html>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/11/08 23:52