回答編集履歴

2

説明追記

2022/06/30 12:07

投稿

hatena19
hatena19

スコア33715

test CHANGED
@@ -1,6 +1,7 @@
1
1
  CSSの`position: sticky;` のような動作を生のJavaScriptで実現したいということでしょうか。
2
2
  JavaScriptの学習のためですか?それともIE対応のためかな?
3
3
 
4
+ **CSS Only**
4
5
  ```css
5
6
  main {
6
7
  .one-page {
@@ -20,6 +21,7 @@
20
21
  }
21
22
  ```
22
23
 
24
+ **同様のことをJSで**
23
25
  ```js
24
26
  //親要素のスクロール量を加味した位置(top, bottom)の取得
25
27
  let elem = document.querySelector('.box');

1

コード追記

2022/06/30 11:51

投稿

hatena19
hatena19

スコア33715

test CHANGED
@@ -20,4 +20,24 @@
20
20
  }
21
21
  ```
22
22
 
23
+ ```js
24
+ //親要素のスクロール量を加味した位置(top, bottom)の取得
25
+ let elem = document.querySelector('.box');
26
+ let rect = elem.getBoundingClientRect();
27
+ let y = rect.top;
28
+ let yBottom = rect.bottom;
23
29
 
30
+ window.addEventListener('DOMContentLoaded', function() {
31
+
32
+ //スクロールイベント時に発火!
33
+ window.addEventListener('scroll', function() {
34
+ console.log(window.scrollY);
35
+ if ( window.scrollY > y && window.scrollY < yBottom ) {
36
+ document.querySelector('.ori').classList.add('is-fixed');
37
+ } else {
38
+ document.querySelector('.ori').classList.remove('is-fixed');
39
+ }
40
+ });
41
+ });
42
+ ```
43
+