一旦用户到达页面上的特定点,自动滚动到特定点/锚点

Once user reaches a particular point on a page, automatically scroll to particular point/achor

本文关键字:滚动 锚点 用户      更新时间:2023-09-26

就是这样:

我要4个div。下面的例子。每个div有一个特定的高度(约1500px),但宽度为100%。每个div都是不同的颜色。

我希望它是这样的,当用户滚动页面并到达一个特定的点时,javascript将启动并自动滚动用户到下一个div。

假设用户在垂直滚动,div #2出现,而div #1消失。当div #1的剩余量约为200px时,页面会自动向下滚动,使div #2与浏览器窗口的顶部齐平。

一个很好的例子:http://thejuly16.com/,它基本上做到了,但不能计算出如何。


1

内容


2

内容


3

内容


4

内容


那个页面没有为我做任何事:/

无论如何,如果我得到你的意思,你应该有一些锚在每个div的顶部,挂钩一些代码滚动事件,检查它的scrollTop()值,并滚动到锚当这个值是在一个理想的范围。你可以检查这个文件和相关的jQuery代码:

$(window).bind('scroll', function(){
    if (($(window).scrollTop() > 1300) && ($(window).scrollTop() < 1350)) {
        window.scrollTo(0,1500);
    }
});

这对用户来说可能是一个奇怪的行为,因为向上滚动是相当混乱的。然而,我们可以通过检查用户在页面上是向上还是向下来解决这个问题,就像在这个fiddle中一样,只是检查最后一个滚动位置是高于还是低于当前滚动位置:

var currentScroll = 0;
var previousScroll = 0;
$(window).bind('scroll', function(){
    currentScroll = $(window).scrollTop();
    if (($(window).scrollTop() > 1300) && ($(window).scrollTop() < 1350) && currentScroll > previousScroll) {
        window.scrollTo(0,1500);
    }
    previousScroll = $(window).scrollTop();
});

显然,您需要在页面中添加尽可能多的if语句。

我有一个解决方案,如下面的代码所示。不知何故,它不能在jsFiddle上工作,但在我的机器上工作。请在您自己的编辑器中尝试

<HTML>
 <HEAD>
  <SCRIPT LANGUAGE="JavaScript">
    var isWorking = false;
var lastScrollPosition
function adjust(oDiv) {
    if(oDiv.scrollTop > lastScrollPosition && !isWorking && oDiv.scrollTop % 400 > 300) {
        isWorking = true
        scroll(oDiv);
    } else
        lastScrollPosition = oDiv.scrollTop;
}
function scroll(div) {
    if(div.scrollTop % 400 > 10) {
        div.scrollTop = div.scrollTop + 10;
        lastScrollPosition = div.scrollTop;
        setTimeout(function(){scroll(div);}, 10);
    } else
        isWorking = false;
}
  </SCRIPT>
 </HEAD>
 <BODY>
  <div style="height: 440px; border: solid 1px red; overflow-Y: auto" onscroll="adjust(this)">
    <div style="height: 400px; border: solid 1px green"></div>
    <div style="height: 400px; border: solid 1px green"></div>
    <div style="height: 400px; border: solid 1px green"></div>
    <div style="height: 400px; border: solid 1px green"></div>
    <div style="height: 100px"></div>
</div>
 </BODY>
</HTML>

我认为jQuery可以提供这个功能。我已经尝试过了,但我在Javascript中的OnClick事件上这样做。在你的情况下,onFocus或任何其他合适的事件,如鼠标悬停等应该工作。