gpt4 book ai didi

javascript - jQuery OnLoad 页面滚动问题

转载 作者:行者123 更新时间:2023-11-30 16:47:39 27 4
gpt4 key购买 nike

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

我在这里写了一个 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 thenjumps 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 hasbeen fully constructed. The handler passed to .ready() is guaranteedto be executed after the DOM is ready, so this is usually the bestplace to attach all other event handlers and run other jQuery code.

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com