Javascript滚动处理

Scroll Handling with Javascript

本文关键字:处理 滚动 Javascript      更新时间:2023-09-26

我是web编程的新手,在我的网站上工作时,我偶然发现了一些奇怪的东西。我使用Wordpress,但这里我必须潜入Javascript代码来完成它。

我想实现的是:我希望人们到达时能看到我网站的标题,但一旦他们在我的网站上阅读了东西就不会被它打扰。我想到的是,如果a)人们在网站的顶部,b)如果他们点击了菜单链接,我希望网站向下滚动。当人们已经在网站上并单击菜单项更改页面时,我希望保持他们之前所在的滚动位置。

我尝试了两个版本:除了每次重新加载站点

时执行该函数之外,这个函数非常有效。
var scroll_position = localStorage.getItem('scroll_position');
var header_height = document.getElementById('masthead').offsetHeight;
var menubar_height = document.getElementById('top-bar').offsetHeight;
var page_height = header_height - menubar_height;
jQuery(function () {
    if (window.pageYOffset == scroll_position){
        jQuery(window).scrollTop(page_height);
    }
    else{
       jQuery(window).scrollTop(scroll_position);
    }
});

但是由于我想只在单击其中一个菜单项时执行该函数,我尝试了:

jQuery("#top-menu ul li a").click(function(){
    if (window.pageYOffset == scroll_position){
        jQuery(window).scrollTop(page_height);
    }
    else{
        jQuery(window).scrollTop(scroll_position);
    }
});

突然间,scroll_position变量不再像以前那样改变值了…

我花了一整天的时间来弄清楚这个问题,如果有人能告诉我我做错了什么,我将非常感激!

根据你给我们的代码,试试这个

jQuery(function () {
    var header_height = document.getElementById('masthead').offsetHeight;
    var menubar_height = document.getElementById('top-bar').offsetHeight;
    var page_height = header_height - menubar_height;
    jQuery("#top-menu ul li a").click(function(e){
        e.preventDefault();
        var scroll_position = localStorage.getItem('scroll_position');
        if (window.pageYOffset == scroll_position){
            jQuery(window).scrollTop(page_height);
        }
        else{
            jQuery(window).scrollTop(scroll_position);
        }
    });
});

我假设header_height, menubar_height和page_height一旦页面加载就不能改变,这就是为什么我们在页面加载时初始化它们,而不是点击。

希望对你有所帮助