- Products -


Software


NEWS


Special



- Knowledge -


Category × Tag



- Like -

公開
作成日:2021/12/10
更新日:2022/6/6

【Javascript】画面表示領域に入ったらクラスを付与する方法

・表示されたらアニメーションを開始したい。というケースがある。これを実現するには、画面表示領域に入ったかどうかを判定する必要がある。

・また実際には、表示領域に入った!というタイミングでクラスを付与し、アニメーションを開始するという実装方法が良く使われている。

使い方


・animationクラスを付けた要素が画面表示領域内に入ったときにアニメ開始用クラスを付与している。

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
    function animation_start() {
        $(".animation").each(function() {
            var hit = $(this).offset().top;
            var scroll = $(window).scrollTop();
            var wHeight = window.innerHeight;

            var start_margin = 100;

            if ((hit + start_margin) < (wHeight + scroll)) {
                $(this).addClass("show");
                console.log("show:" + $(this).text());
            }
        });
    }

    $(function() {
        $(window).on("scroll", function() {
            animation_start();
        });

        animation_start();
    });
</script>
<style>
    .show {
        animation: anime1 5s ease 0s infinite alternate;
    }

    @keyframes anime1 {
        0% {
            color: black;
        }

        30% {
            color: yellow;
        }

        60% {
            color: blue;
        }

        100% {
            color: green;
        }
    }
</style>


補足


・高さに関するプロパティはいくつかあるので要注意。
https://web-designer.cman.jp/javascript_ref/window/size/

参考


https://www.attend.jp/html-190912


Category



Tag




関連記事


{{tmp.name}}

{{article.category}} {{article.title}}