0

私が取り組んでいるプロジェクト 新しいコンテンツにスクロールするときに、上部の div のヘッダー タイトル (例: We Thank You) を変更したいと考えています。タイトルごとに異なる画像を使用していますが、css/html を使用してこれを実現するにはどうすればよいですか? ここにページがありますhttp://2facced.com/marcecko/

4

1 に答える 1

0

jQuery を使用すると、これがはるかに簡単になるため、スクロール イベントとスクロール位置をキャッチできます。CDN から jQuery を含める方法を調べてください。jQuery の Web サイトにいくつかの例があります。

jQuery を含めた後、次のスクリプトを追加します。

<script language="javascript" type="text/javascript">
$(document).ready(function(){//Anything inside this function runs once the page is finished loading
    $(window).scroll(function() { //jQuery function that adds a handler to run code anytime the user scrolls.
        var changeThreshold1 = 1000;//the first point on the page where we want to trigger a change
        var changeThreshold2 = 2000;//the second
        var changeThreshold3 = 3000;//you ge the idea
        var changeThreshold4 = 4000;
        if($(window).scrollTop() < changeThreshold1){//If the user has not yet scrolled past the first point, or has scrolled back above teh first point
            $('#header').css('background-image','[image source 1]'); //changes the background image of the element with the header ID to the first image source replace [image source 1] with the actual image file name
        }else if($(window).scrollTop() >= changeThreshold1 AND $(window).scrollTop() < changeThreshold2){//if the user has scrolled to the range between points 1 and 2
            $('#header').css('background-image','[image source 2]');
        }else if($(window).scrollTop() >= changeThreshold2 AND $(window).scrollTop() < changeThreshold3){//if the user has scrolled to the range between points 2 and 3
            $('#header').css('background-image','[image source 3]');
        }else if($(window).scrollTop() >= changeThreshold3 AND $(window).scrollTop() < changeThreshold4){//if the user has scrolled to the range between points 3 and 4
            $('#header').css('background-image','[image source 4]');
        }else if($(window).scrollTop() >= changeThreshold4 ){//if the user has scrolled to the range beyond point 4
            $('#header').css('background-image','[image source 5]');
        }else{//a failsafe default incase anything gets screwed up
            $('#header').css('background-image','[image source default]');
        }
    });
});
</script>

編集-コメントの返信:

あなたの質問から、HTML と JavaScript の仕組みについて誤解していると思われます。要素が現在表示可能領域にあるポイントまでユーザーがスクロールしたときに、スクリプトを実行するようにトリガーする方法はありません。あなたがしなければならないことは、測定または明示的に設定することによって、トリガーがページの上部から何ピクセルであるかを知ることです。次に、ユーザーがスクロールした距離を検出し、その既知の測定値と照合します。彼らがそのポイントを通過した場合は、変更を行います。したがって、ページ上の 1 つのスクリプトが、ユーザーがスクロールするタイミングと移動距離の検出に基づいて、すべての変更を行います。より良い例とより詳細なメモを提供するために、回答を修正しました。理解を深めるのに役立つことを願っています。

于 2013-10-15T20:02:32.560 に答える