0

我正在处理的项目我想在滚动到新内容时更改顶部 div 中的标题标题(例如,我们谢谢你)。为每个标题使用不同的图像,如何通过 css/html 实现这一点?这是页面http://2facced.com/marcecko/

4

1 回答 1

0

使用 jQuery 使这更容易,因此您可以捕获滚动事件和滚动位置。请查看如何从 CDN 中包含 jQuery,jQuery 的网站上有几个示例。

包含 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 的工作方式存在误解。当用户滚动到元素现在在其可视区域中的点时,无法触发脚本运行。您需要做的是通过测量或明确设置来了解触发器距页面顶部的像素数。然后检测用户滚动了多远,并根据已知测量值进行检查。如果他们已经通过了这一点,那么你就做出改变。因此,页面上的一个脚本会根据检测用户何时滚动以及他们走了多远来完成所有更改。我已经修改了我的答案,以便为您提供更好的示例和更详尽的说明。我希望它可以帮助您更好地理解。

于 2013-10-15T20:02:32.560 回答