jquery 平滑滚动使用 Visual Studio 代码



我正在尝试在我的网页上使用jquery设置平滑滚动。

我正在从这个例子开始工作:https://css-tricks.com/snippets/jquery/smooth-scrolling/

当我将其复制并粘贴到 js 小提琴中时,它工作正常。但由于某种原因,它根本不在我的网站上工作。如您所见,我已经将我的脚本.js文件链接到我的索引.html,并在控制台中使用控制台.log消息对此进行了检查。

这是我的网页:

!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700|Ubuntu:400,500" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<title>Zane Mersky</title>
</head>
<body>
<header>
<div class="wrapper">
<div class="heading">
<div class="logo">
<h1>Heading</h1>
</div>
<nav>
<ul>
<li><a href="#philosophy">My Philosophy</a></li>
<li><a href="">My Classroom</a></li>
<li><a href="">Professional Development</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
</div>
</div>
<div class="intro">
<div class="img-container">
<img src="/assets/IMG_6543.JPG" alt="">
</div>
<div class="left-intro"></div>
<div class="right-intro">
<div class="quote">
<h3>"Childhood is not a race to see how quickly a child can read, write and count. It is a small window of time to learn and develop at the pace that is right for each individual child. <br class="break"> Earlier is not better."</h3>
<h3 class="author">-Magda Gerber</h3>
</div>
</div>
</div>
</header>
<main>
<section class="philosophy">
<h1 id="philosophy">My Philosophy</h1>
<div class="paragraph wrapper">
</div>
</section>
<section class="about">
<h1>About Me</h1>
</section>          
</main>      
</body>
</html>

这是我正在使用的jquery:

// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^//, '') == this.pathname.replace(/^//, '') 
&& 
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});

有谁知道我做错了什么?

问题是因为你把JS文件的链接放在了头上。把它放在身体的底部,它会起作用。

始终将指向JS文件的链接放在正文的结束标记之前。

这是因为您可能在头部中添加了脚本,并且在脚本在头部执行后加载文档。要使您的脚本正常工作,您应该将其添加到正文底部或添加一个脚本来检查文档是否已准备就绪,就像我在此处的代码片段中所做的那样:

https://codebrace.com/editor/b071c752c

$("document").ready(...在加载文档后加载脚本。

最新更新