gpt4 book ai didi

javascript - 如何减慢单页平滑滚动?

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:35 25 4
gpt4 key购买 nike

我已将一些 javascript 添加到导航栏标记的单页网站中。所以现在当用户点击标题时,他们会直接进入该部分。目前它直接进入该部分,我如何减慢它的速度,以便从导航到所选部分的平滑滚动过渡?

这是我的代码——

$('a[href^="#"]').click(function(event) {
var id = $(this).attr("href");
var target = $(id).offset().top;
$('html, body').animate({
scrollTop: target
}, 500);
event.preventDefault();
});

function getTargetTop(elem) {
var id = elem.attr("href");
var offset = 60;
return $(id).offset().top - offset;
}


$(window).scroll(function(e) {
isSelected($(window).scrollTop())
});

var sections = $('a[href^="#"]');

function isSelected(scrolledTo) {

var threshold = 100;
var i;

for (i = 0; i < sections.length; i++) {
var section = $(sections[i]);
var target = getTargetTop(section);

if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
sections.removeClass("active");
section.addClass("active");
}

};
}
header {
height: 50px;
}

nav {
text-align: center;
padding: 10px;
margin-top: 20px;
}

nav a {
color: #000000;
transition: all 0.2s ease-in-out 0s;
text-decoration: none;
display: inline-block;
padding: 5px;
border-bottom: 2px solid transparent;
}

nav a:link {
color: #000000;
text-decoration-line: none;
}

nav a:nth-of-type(1):hover {
border-color: rgb(255, 29, 142);
}

nav a:nth-of-type(2):hover {
border-color: rgb(133, 52, 146);
}

nav a:nth-of-type(3):hover {
border-color: rgb(255, 128, 55);
}

nav a:nth-of-type(4):hover {
border-color: rgb(0, 182, 223);
}

nav a:nth-of-type(5):hover {
border-color: rgb(63, 190, 150);
}

nav a:nth-of-type(6):hover {
border-color: rgb(255, 222, 32);
}

nav a:hover {
color: #000000;
}

#logo {
width: 100%;
max-width: 100%;
height: 750px;
}

#whatwedo {
width: 100%;
max-width: 100%;
height: 750px;
}

#whoweare {
width: 100%;
max-width: 100%;
height: 750px;
}

#partners {
width: 100%;
max-width: 100%;
height: 750px;
}

#contact {
width: 100%;
max-width: 100%;
height: 750px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<nav>
<a href="#logo">Home</a>
<a href="#whatwedo">What we do</a>
<a href="#whoweare">Who we are</a>
<a href="#partners">Who we work with</a>
<a href="#contact">Say hello</a>
<a href="Blog">Blog</a>
</nav>

</header>

<section id="logo">Logo</section>

<section id="whatwedo">What we do </section>

<section id="whoweare"> Who we are </section>

<section id="partners"> Our Partners </section>

<section id="contact"> Contact </section>

最佳答案

你必须修改动画的值并像这样放一个更大的值:

$('html, body').animate({
scrollTop: target
}, 2000);

2000 表示 2 秒

关于javascript - 如何减慢单页平滑滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46485819/

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