【发布时间】:2019-01-29 18:21:46
【问题描述】:
我试图在锚点之间创建平滑滚动,但我似乎无法让它工作 - 我不确定这是因为我的网站使用水平滚动而不是垂直滚动,还是我只是遗漏了一些明显的东西(我是编码新手)。
我已经尝试过 CSS 技巧教程 (https://css-tricks.com/snippets/jquery/smooth-scrolling/)。
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Nathan Wilson</title>
<meta name="description"
content="Hi, I'm Nathan Wilson, a Graphic Designer based in Nottingham, U.K.">
<meta name="keywords"
content="Nathan, Wilson, Graphic, Design, Designer, Portfolio, Nottingham, UK, U.K, U.K., England, East, Midlands, Website, Web, Logo, Branding, Rebrand, Rebranding, Junior, Local">
<meta name="author" content="Nathan Wilson">
<link rel="stylesheet" href="css/style.css">
<link rel="icon" href="images/logo.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/main.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nanum+Myeongjo:700,800" rel="stylesheet">
</head>
<body>
<div class="logo">
<img src="images/logo.png">
</div>
<div id="navbar">
<div class="tab1">
<a class="link1" href="#home">
<div class="text1">Home</div>
</a></div>
<div class="tab2">
<a class="link2" href="#work">
<div class="text2">Work</div>
</a></div>
<div class="tab3">
<a class="link3" href="#about">
<div class="text3">About</div>
</a></div>
</div>
<div id="container">
<div id="fullscreen">
<div class="box home" id="home">
<div class="heading">
<h1>Hi,</h1>
<h2>I'm Nathan Wilson</h2>
<h3>a Graphic Designer based in Nottingham, U.K.</h3>
</div>
</div>
<div class="box work" id="work">
</div>
<div class="box about" id="about">
</div>
</div>
</div>
</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
};
});
}
}
});
感谢您的帮助。
【问题讨论】:
-
你添加这个css html { scroll-behavior: smooth; } ?
-
@NishargShah 是的,我已经尝试过使用滚动行为,但仍然没有运气。
-
让我找,等会儿
-
你可以在没有任何 js 或 jquery 的情况下做同样的事情!你想试试吗?
-
@NishargShah 我愿意试一试
标签: jquery html css scroll smooth-scrolling