css - 滚动时替换顶部粘性 div 上的标题

标签 css html

我正在处理的元素 我想在滚动到新内容时更改顶部 div 中的页眉标题(例如 We Thank You)。为每个标题使用不同的图像,我怎样才能通过 css/html 实现这一点?这是页面 http://2facced.com/marcecko/

最佳答案

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

关于css - 滚动时替换顶部粘性 div 上的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19386430/

相关文章:

javascript - 如何在 react 中用鼠标滚轮水平滚动表格?

html - Div 不在带有边距自动的父 div 中居中

jquery - 禁止在 div 中复制?

javascript - 使用粘性 div 平滑滚动

javascript - 在 jQuery 上动态绑定(bind)函数

html - Rails/Bootstrap/css/响应式图像尺寸小

javascript - jQuery Select Checkbox 当文本存在时,从打印中隐藏未选中的行

javascript - 使用 AngularJs 和 PHP 显示从 MYSQL 收集的数据到 html 页面

html - 在另一个元素旁边有导航框

css - 设置 SCSS 颜色变量将不起作用