teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

過去に似た質問があったので、それを参考にしつつコードを変更しました。 https://teratail.com/questions/254960

2021/12/29 03:09

投稿

sucota
sucota

スコア1

title CHANGED
File without changes
body CHANGED
@@ -7,51 +7,56 @@
7
7
 
8
8
  今だとセクションが増えるごとに(セクション1、セクション2・・・)コードを記述しないといけないが、
9
9
  これを、セクションが増えても記述しなくても大丈夫なようにしたい。
10
+ ⇒ これは解決
10
11
 
12
+ 別の問題が発生して解決できません
13
+
14
+ sectionに入るごとに、
15
+ number-1 number-2 number-3・・・
16
+ と付くようにはなりました。
17
+ やりたいことは、ここから、例えば、sectionの2つ目の時は、
18
+ number-2のみのclassが付与されるようにしたいです。
19
+ 今だと、number-1 number-2の様に複数付いてしまいます。
20
+
21
+ このコードからどう変更すればいいでしょうか?
22
+
23
+
11
24
  ### 該当のソースコード
12
25
 
13
26
  HTML
14
27
  ```
15
- <div class="section section1">
28
+ <section>
29
+ title
16
- <div class="section-content">セクション1</div>
30
+ detail
17
- </div>
31
+ </section>
18
- <div class="section section2 target-area2">
32
+ <section>
33
+ title
19
- <div class="section-content">セクション2</div>
34
+ detail
20
- </div>
35
+ </section>
21
- <div class="section section3 target-area3">
36
+ <section>
37
+ title
22
- <div class="section-content">セクション3</div>
38
+ detail
23
- </div>
39
+ </section>
24
- <div class="section section4">
25
- <div class="section-content">セクション4</div>
26
- </div>
27
- <div class="section section5">
28
- <div class="section-content">セクション5</div>
29
- </div>
30
40
  ```
31
41
  javascript(jQuery)
32
42
  ```
33
- jQuery(window).scroll(function() {
43
+ $(window).on('scroll', function() {
44
+ add_class_in_scrolling( $('section') );
45
+ });
34
46
 
47
+ function add_class_in_scrolling( $target ) {
35
- let scrollTop2 = jQuery(window).scrollTop(); // スクロール上部の位置
48
+ var winScroll = $(window).scrollTop();//スクロールの上下位置を取得
36
- let areaTop2 = jQuery(".target-area2").offset().top; // 対象エリア上部の位置
49
+ var winHeight = $(window).height();//ウィンドウ高さを取得
37
- let areaBottom2 = areaTop2 + jQuery(".target-area2").innerHeight(); // 対象エリアの下部の位置
38
-
39
- if (scrollTop2 > areaTop2 && scrollTop2 < areaBottom2) {
50
+ var scrollPos = winScroll + winHeight;//上記の合計(スクロールポジション)
51
+ $target.each(function(i){
52
+ if($(this).offset().top < scrollPos) {
40
- jQuery("body").addClass("is-in2"); // スクロールが対象エリアに入った場合
53
+ $("body").addClass('number-' + (i+1)); // スクロールが対象エリアに入った場合
41
- } else {
42
- jQuery("body").removeClass("is-in2"); // スクロールが対象エリアから出ている場合
43
- }
54
+ }
44
-
45
- let scrollTop3 = jQuery(window).scrollTop(); // スクロール上部の位置
46
- let areaTop3 = jQuery(".target-area3").offset().top; // 対象エリアの上部の位置
47
- let areaBottom3 = areaTop3 + jQuery(".target-area3").innerHeight(); // 対象エリアの下部の位置
48
-
49
- if (scrollTop3 > areaTop3 && scrollTop3 < areaBottom3) {
50
- jQuery("body").addClass("is-in3"); // スクロールが対象エリアに入った場合
51
- } else {
55
+ else {
52
- jQuery("body").removeClass("is-in3"); // スクロールが対象エリアから出ている場合
56
+ $("body").removeClass('number-' + (i+1));// スクロールが対象エリアから出ている場合
53
- }
57
+ }
54
58
  });
59
+ }
55
60
  ```
56
61
 
57
62
  ご教授お願いします。