【问题标题】:Replace header on top sticky div while scrolling滚动时替换顶部粘性 div 上的标题
【发布时间】:2013-10-17 04:27:23
【问题描述】:

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

【问题讨论】:

  • 向下滚动时是否要更改页面标题?
  • 是的,所以当我点击某些位置时,页面标题也会发生变化。 “我们谢谢你”“产品”……“品牌”……“系列”……等等……
  • OK 看看我在做什么
  • 你必须使用 Javascript document.title = "This is the new page title.";
  • 好的,谢谢。你能给我看一个完整的脚本示例吗?

标签: css html


【解决方案1】:

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

【讨论】:

  • 谢谢,这是有道理的。我是否必须在我希望标题更改的每个点插入此脚本?我以前从未这样做过,我不确定如何标记它
  • 请查看我编辑的答案以获得回复,因为太长了,无法作为评论留下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 2019-06-15
  • 2013-10-19
  • 2013-09-03
  • 1970-01-01
相关资源
最近更新 更多