javascript - jQuery OnLoad 页面滚动问题

标签 javascript jquery html scrollto

我正在开发一个网站,用户可以使用地址栏中的 # 值从其他页面导航到页面的不同部分。

我在这里写了一个 jQuery 函数来处理滚动:

jQuery.fn.scrollToDiv = function(navheight)
{
    if (!navheight)
    {
        navheight = 30;
    }

    var offset = this.offset();
    var offsetTop = offset.top;
    var totalScroll = offsetTop-navheight-27;
    $('body,html').animate({
            scrollTop: totalScroll
    }, 500);
}

我在两种不同的情况下调用该函数;当用户单击对象位于当前页面上的链接时,以及当用户单击将他们带到另一个页面然后滚动到该元素的链接时。见下文:

当您在页面上时:

$('.gotoPage').on('click', function(e)
{
    e.preventDefault();
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    if (sPath != '' && sPath != 'home')
    {
        var href = $(this).attr('href');

        handleScroll(href);
    }
});

当您不在页面上时:

$(document).ready(function(e) 
{    
    var target = window.location.hash;

    if (target != '')
    {
        $(target).scrollToDiv(30);
    }
});

当您在页面上并单击链接时,它可以完美运行,但是当您不在该页面上时,它会按照您的预期将您带到后续页面,但不会滚动到所需的元素.

如果您需要更多信息,请告诉我

提前致谢

编辑:添加函数handleScroll(target)

function handleScroll(target)
{
    if (target != '')
    {
        $(target).scrollToDiv(30);
    }
}

最佳答案

根据您的评论:

I've noticed when refreshing the page is that it scrolls down then jumps back to the top of the page

看来您的脚本确实有效,但之后会受到影响。 我相信有一些资源作为额外的 css 代码或图像在滚动动画生效时没有被考虑在内并且因为该功能通过 top 偏移工作 - 你必须确保你'在加载所有可能影响文档高度或元素偏移量的资源后重新使用它。

因此,不要在 .ready() 中使用您的脚本,而是使用 .load()

.ready() vs. .load()

In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

关于javascript - jQuery OnLoad 页面滚动问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30999815/

相关文章:

javascript - 如何从 JavaScript 数组值中找到所有长度的所有排列?

javascript - 由于 json,Ajax 表单无法工作(解析器错误抛出 : SyntaxError: JSON. 解析:JSON 数据的第 1 行第 1 列处的数据意外结束)

javascript - Jquery获取和设置html字符串某些部分的css属性

php - 从网站复制文本,附加复制文本的链接?

javascript - DIV 在 iframe 上扩展

javascript - VIES 增值税号验证

javascript - HTML/CSS 图像缩放

javascript - HTML/JavaScript 应用程序的 LDAP 身份验证

javascript - 打字完成后提交表格吗?

javascript - ajax post 成功后淡入淡出