JS実装で気を付けるポイント

この記事を読むのにかかる時間 1未満

①pushをするときにaaa[0]などとオブジェクトを入れることはできない。

②画面いっぱいのナビゲーションを表示したとき、背景のスクロールができてしまう
 →bodyにoverflow:hiddenwを設定する
https://zenn.dev/lclco/articles/f5b20817a15b9a

③imgの高さ要素を取得したいが0になる
→ aaa.addEventListener(“load”,function(){…として、ロードが終わった後に処理をするようにすれば改善した
ただ、キャッシュなどで既にload状態だと逆に機能しなくなるので、以下のように修正

            if(target.complete){
                //処理
            }else{
                target.addEventListener("load",function(){
                    //処理
                })
            }

④jsでマージン含めた高さを取得するのはちょっと面倒

function getOuterHeightWithMargin(element) {
    const style = window.getComputedStyle(element);
    const height = element.getBoundingClientRect().height;
    const marginTop = parseFloat(style.marginTop);
    const marginBottom = parseFloat(style.marginBottom);

    return height + marginTop + marginBottom;
}

// 使用例
const element = document.querySelector('#yourElement');
const outerHeightWithMargin = getOuterHeightWithMargin(element);
console.log(outerHeightWithMargin);