【发布时间】:2020-07-17 21:06:09
【问题描述】:
我正在开发一个网站,并且在我的导航栏中有一个“功能”链接。在主页上,如果单击“功能”,我将其向下滚动到带有 id="expo-features" 的 H1(此处简化):
<div class="topnav-right">
<a href="#expo-features">Features</a>
<a href="register.php">Registration</a>
<a href="booth.php">Reserve A Booth</a>
<a href="sponsor.php">Sponsor Event</a>
<a href="contact.php">Contact</a>
</div>
/*Scrolls to this section*/
<h1 id="expo-features">Expo Features</h1>
我在头部添加了一些脚本来完成这项工作:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
一切都很好!它完美地滚动到 expo-features id。当然,由于这是在我的导航中,因此它会出现在其他页面上。所以我需要它能够链接到同一部分(显然它不会滚动到它,因为它会转到不同的页面——但这没关系)。在我的一些页面上,这是有效的。
但是,我有 2 个页面具有自己的唯一 id# 链接,并且头部具有相同的脚本。但是现在位于导航中的“功能”按钮不会跳到那 2 页上。我不知道为什么?
长话短说:here is my website
- 导航中的“功能”按钮#链接到主页上的部分
- 适用于主页、注册页面和联系页面
- “功能”按钮在 booth page 和 sponsor page 上不起作用,我认为这是因为这些页面有自己独特的 id# 链接,并且头部有相同的脚本。
- 是的,在其他页面上,“功能”按钮 href="https://virtualdigitalexpo.com/#expo-features"
【问题讨论】:
-
你知道你可以通过one line of css code做到这一点
-
如果你检查浏览器的控制台,你会看到这个错误Uncaught TypeError: Cannot read property 'top' of undefined,当你转到错误行时,你会看到它是这个
scrollTop: $(hash).offset().top,这意味着$(hash).offset()未定义,这意味着if (this.hash !== "")没有像你想象的那样工作,尝试不仅检查"",还要检查null和@ 之类的东西987654332@ 并尝试查明为什么this.hash没有得到正确值的原因
标签: javascript jquery html smooth-scrolling hashtag