[英]jQuery scroll to section on another page
我有一个网站,它使用 jQuery 在几个部分(在 page1.html 中)之间滚动。 现在,我在网站上添加了另一个页面 (page2.html)。
我希望 page2.html 的 header 中的链接链接回 page1.html 中的相应部分。
在 page2.html 我写道:
<li><a href="page1.html#splash">Home</a></li>
这链接回page1.html#splash
。 但是在 page1 上,该站点不会滚动到相应的部分。
我的 JavaScript 是:
$(document).ready(function(){
$('a[href=\\#]').click(function(e){
e.preventDefault();
$('nav').removeClass('visible');
$('html,body').stop().animate({scrollTop: $('.'+$(this).data('scrollto')).offset().top-65 }, 700, 'easeInOutExpo', function(){});
});
我已经尝试过的:
我尝试将在其他地方找到的以下代码添加到 page1.html:
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
}
});
});
</script>
但是没有滚动到右侧部分,控制台显示以下错误: index.html:19 Uncaught ReferenceError: $ is not defined
坦率地说,由于缺乏该领域的专业知识,我被困在这一点上。
当来自另一个页面时,如何管理该站点实际上滚动到正确的部分?
离开页面后,上一页的 JavaScript 将无法控制它。 因此,您需要使用 jQuery 在新页面加载时对其进行处理。 将此代码放在 page1.html 上,将注释更改为滚动命令:
$(document).ready(function() { if (window.location.href.includes('#splash')) { let animationTime = 100; $('html, body').animate({ scrollTop: $('.splash').offset().top }, animationTime); } });
Uncaught ReferenceError: $ is not defined
当您的页面没有得到JQuery
时会出现此类错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.