前提・実現したいこと
window.onloadで特定のIDの位置まで表示をずらしたいのですが
テスト中に以下のエラーメッセージが発生しました。
TOPが取得できないとのことなのですがwindow.onloadのタイミングで高さがないという事はあり得るのでしょうか?
発生している問題・エラーメッセージ
Uncaught TypeError: Cannot read properties of null (reading 'getBoundingClientRect') at window.onload
JavaScript
JavaScript
1<article class="content_li" id="content0"> 2 <form method="post" action="" enctype="multipart/form-data"> 3 <input type="hidden" name="types" value="0" /> 4 <h1></h1> 5 <img src="/photo/call_img.php?id=10&cl=9"> 6 <p style="text-align:center;">8592年01月19日</p> 7 <p></p> 8 <input type="hidden" value="0,0" id="position0" name="position0"/> 9 <input type="submit" id="submit" class="clickEvent" name="sender" value="ImageList0編集"/> 10 <input type="submit" id="submit" class="clickEvent" name="sender" value="ImageList0削除"/> 11 </form> 12</article> 13<script> 14 /**************** 15 * 表示位置の変更 16 ****************/ 17 window.onload = function (){ 18 const flag = true; 19 if(flag){ 20 const targetId = "content0"; 21 const targetElement = document.querySelector(targetId);//idのエレメント 22 const targetOffsetTop = window.pageYOffset + targetElement.getBoundingClientRect().top;//距離を取得 23 window.scrollTo({ 24 top: targetOffsetTop, 25 behavior: "smooth" 26 }); 27 }else{window.scrollTo(0,0); } 28 } 29</script>
試したこと
DOMContentLoadedや
window.addEventListener('load', function()
でも上手くいきませんでした。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/01/20 02:51