回答編集履歴
2
コード修正
answer
CHANGED
@@ -55,7 +55,6 @@
|
|
55
55
|
const targetElement = document.getElementById( "footer" ) ;
|
56
56
|
const ClientRect = targetElement.getBoundingClientRect() ;
|
57
57
|
const previousElementRect = targetElement.previousElementSibling.getBoundingClientRect() ;
|
58
|
-
console.log(window.innerHeight, previousElementRect.top + previousElementRect.height);
|
59
58
|
if(window.innerHeight > (previousElementRect.top + previousElementRect.height + ClientRect.height)){
|
60
59
|
targetElement.classList.add('fixed');
|
61
60
|
}else {
|
1
説明追記
answer
CHANGED
@@ -15,4 +15,52 @@
|
|
15
15
|
height: 50px;
|
16
16
|
background-color: pink;
|
17
17
|
}
|
18
|
-
```
|
18
|
+
```
|
19
|
+
|
20
|
+
---
|
21
|
+
質問のJSコードでなぜうまくいかない場合があるのか考察してみました。
|
22
|
+
まず、フッターに fixed を設定しておいて、下記のコードで動作を確認してみました。
|
23
|
+
```js
|
24
|
+
window.addEventListener('load', footerFixed);
|
25
|
+
window.addEventListener('resize', footerFixed);
|
26
|
+
function footerFixed(){
|
27
|
+
const targetElement = document.getElementById( "footer" ) ;
|
28
|
+
const ClientRect = targetElement.getBoundingClientRect() ;
|
29
|
+
console.log(window.innerHeight, ClientRect.top + ClientRect.height);
|
30
|
+
}
|
31
|
+
```
|
32
|
+
画面サイズを変更するとコンソールに下記のように出力されます。
|
33
|
+
```
|
34
|
+
376 376
|
35
|
+
377 376.8000183105469
|
36
|
+
378 377.6000061035156
|
37
|
+
379 379.20001220703125 ※
|
38
|
+
380 380
|
39
|
+
381 380.8000183105469
|
40
|
+
382 381.6000061035156
|
41
|
+
383 383.20001220703125 ※
|
42
|
+
384 384
|
43
|
+
```
|
44
|
+
たまに、window.innerHeight より ClientRect.top + ClientRect.height が大きい場合があります。
|
45
|
+
(※の行)
|
46
|
+
|
47
|
+
画面高を変更することで、 ClientRect.top も変化する。相互に変化するものを比較するということは非常に危なっかしい状態であると推測できます。
|
48
|
+
|
49
|
+
そこで、画面高を変更しても変化しないものを基準にすればいいのでは、ということで、一つ前の要素の下辺位置にフッターの高さを足したものと比較するコードを書いてみました。
|
50
|
+
|
51
|
+
```js
|
52
|
+
window.addEventListener('load', footerFixed);
|
53
|
+
window.addEventListener('resize', footerFixed);
|
54
|
+
function footerFixed(){
|
55
|
+
const targetElement = document.getElementById( "footer" ) ;
|
56
|
+
const ClientRect = targetElement.getBoundingClientRect() ;
|
57
|
+
const previousElementRect = targetElement.previousElementSibling.getBoundingClientRect() ;
|
58
|
+
console.log(window.innerHeight, previousElementRect.top + previousElementRect.height);
|
59
|
+
if(window.innerHeight > (previousElementRect.top + previousElementRect.height + ClientRect.height)){
|
60
|
+
targetElement.classList.add('fixed');
|
61
|
+
}else {
|
62
|
+
targetElement.classList.remove('fixed');
|
63
|
+
}
|
64
|
+
}
|
65
|
+
```
|
66
|
+
当方のテストでは安定して動作してます。
|