平滑滚动时,点击一个锚链接

我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。

使用锚链接,我可以使页面滚动到锚,并引导用户到那里。

有没有办法使滚动流畅?

但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?

1030767 次浏览

现在有这是当地人的做法:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();


document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});

目前只有最先进的浏览器支持这一功能。


对于旧的浏览器支持,你可以使用jQuery技术:

$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();


$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});

这是小提琴:http://jsfiddle.net/9SDLw/


如果你的目标元素没有ID,并且你通过它的name链接到它,使用:

$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);


return false;
});

为了提高性能,你应该缓存$('html, body')选择器,这样当点击锚时它就不会运行每一次:

var $root = $('html, body');


$('a[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);


return false;
});

如果你想要更新URL,在animate回调中完成:

var $root = $('html, body');


$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');


$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});


return false;
});

正确的语法是:

//Smooth scrolling with links
$('a[href^=\\#]').on('click', function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});


// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
$('html,body').animate({scrollTop:$(location.hash).offset().‌​top}, 500);
});

# EYZ0:干

function smoothScrollingTo(target){
$('html,body').animate({scrollTop:$(target).offset().​top}, 500);
}
$('a[href^=\\#]').on('click', function(event){
event.preventDefault();
smoothScrollingTo(this.hash);
});
$(document).ready(function(){
smoothScrollingTo(location.hash);
});

href^=\\#的解释:

  • ^表示它匹配包含#字符的内容。因此,只匹配,以确保它是同一个页面的链接(感谢彼得黄的建议)。
  • \\是因为#是css选择器中的一个特殊字符,所以我们必须转义它。
$('a[href*=#]').click(function(event){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
event.preventDefault();
});

这对我来说是完美的

使用JQuery:

$('a[href*=#]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});

添加:

function () {
window.location.hash = href;
}

是否使垂直偏移量无效

top - 72

Firefox和IE浏览器,但Chrome浏览器没有。基本上,页面平滑地滚动到基于偏移量它应该停止的位置,但然后向下跳转到没有偏移量的页面所在的位置。

它确实将哈希添加到url的末尾,但按下back并不会让你回到顶部,它只是从url中删除哈希,并留下它所在的查看窗口。

这是我使用的完整js:

var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top - 120
}, 500, function () {
window.location.hash = href;
});
return false;
});

我对"/xxxxx#asdf"和"#asdf" href锚都这样做了

$("a[href*=#]").on('click', function(event){
var href = $(this).attr("href");
if ( /(#.*)/.test(href) ){
var hash = href.match(/(#.*)/)[0];
var path = href.match(/([^#]*)/)[0];


if (window.location.pathname == path || path.length == 0){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
window.location.hash = hash;
}
}
});
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
< p >官员: # EYZ0 < / p >

以下是我为多个链接和锚点实现的解决方案,用于平滑滚动:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/ 如果你在导航div中设置了导航链接,并声明了这样的结构:

<a href = "#destinationA">

和你相应的锚标签目的地如下:

<a id = "destinationA">

然后把这个加载到文档的头部:

    <!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>


<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>


<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>


<script type = "text/javascript">
$(document).ready(function()
{
// Scroll the whole document
$('#menuBox').localScroll({
target:'#content'
});
});
</script>

感谢@Adriantomic

如果你在页面上有一个简单的按钮向下滚动到一个div,并希望后退按钮通过跳到顶部来工作,只需添加以下代码:

$(window).on('hashchange', function(event) {
if (event.target.location.hash=="") {
window.scrollTo(0,0);
}
});

这也可以扩展到跳转到不同的div,通过读取哈希值,并像Joseph Silbers的答案一样滚动。

此解决方案也适用于以下url,而不会破坏指向不同页面的锚点链接。

http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor


./index.html
./index.html#anchor

等。

var $root = $('html, body');
$('a').on('click', function(event){
var hash = this.hash;
// Is the anchor on the same page?
if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
$root.animate({
scrollTop: $(hash).offset().top
}, 'normal', function() {
location.hash = hash;
});
return false;
}
});

我还没有在所有浏览器中测试这个功能。

我建议你编写这样的泛型代码:

$('a[href^="#"]').click(function(){


var the_id = $(this).attr("href");


$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');


return false;});

你可以在这里看到一篇非常好的文章:jquery-effet-smooth-scroll-defilement-fluide

这将使jQuery很容易识别目标哈希并知道何时何地停止。

$('a[href*="#"]').click(function(e) {
e.preventDefault();
var target = this.hash;
$target = $(target);


$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});

不要忘记offset()函数将元素的位置传递给文档。所以当你需要滚动你的元素相对于它的父元素时你应该使用这个;

    $('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});

关键点是获得scroll-div的scrollTop,并将其添加到scrollTop。如果你不这样做,position()函数总是会给你不同的位置值。

$("a").on("click", function(event){
//check the value of this.hash
if(this.hash !== ""){
event.preventDefault();


$("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);


//add hash to the current scroll position
window.location.hash = this.hash;


}






});

经过测试和验证的代码

<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("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
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){


// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>

给出的答案可以工作,但会禁用外向链接。下面的版本与额外的奖金放松(摇摆)和尊重外向的链接。

$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();


var target = this.hash;
var $target = $(target);


$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});

超文本标记语言

<a href="#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>

或使用绝对完整的URL

<a href="https://somewebsite.com/#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>

jQuery

$j(function() {
$j('a.smooth-scroll').click(function() {
if (
window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&  window.location.hostname == this.hostname
) {
var target = $j(this.hash);
target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$j('html,body').animate({
scrollTop: target.offset().top - 70
}, 1000);
return false;
}
}
});
});

现在的浏览器要快一些。setInterval可能有用。现在这个功能在Chrome和Firefox中运行良好。(safari有点慢,不用IE)

function smoothScroll(event) {
if (event.target.hash !== '') { //Check if tag is an anchor
event.preventDefault()
const hash = event.target.hash.replace("#", "")
const link = document.getElementsByName(hash)
//Find the where you want to scroll
const position = link[0].getBoundingClientRect().y
let top = 0


let smooth = setInterval(() => {
let leftover = position - top
if (top === position) {
clearInterval(smooth)
}


else if(position > top && leftover < 10) {
top += leftover
window.scrollTo(0, top)
}


else if(position > (top - 10)) {
top += 10
window.scrollTo(0, top)
}


}, 6)//6 milliseconds is the faster chrome runs setInterval
}
}

我很惊讶没有人发布一个本地解决方案,也负责更新浏览器位置哈希匹配。下面就是:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

参见教程:http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml

对于带有粘头的站点,scroll-padding-top CSS可用于提供偏移量。

谢谢分享,约瑟夫·西尔伯。以下是你2018年的ES6解决方案,其中有一些小改动,以保持标准行为(滚动到顶部):

document.querySelectorAll("a[href^=\"#\"]").forEach((anchor) => {
anchor.addEventListener("click", function (ev) {
ev.preventDefault();


const targetElement = document.querySelector(this.getAttribute("href"));
targetElement.scrollIntoView({
block: "start",
alignToTop: true,
behavior: "smooth"
});
});
});

CSS3的新热点。这比本页列出的所有方法都要简单得多,而且不需要Javascript。只需输入下面的代码到你的css和所有的链接指向你自己的页面内的位置将有一个平滑的滚动动画。

html{scroll-behavior:smooth}

之后,任何指向div的链接都将平滑地滑到这些部分。

<a href="#section">Section1</a>

编辑:对于那些对上面的一个标签感到困惑的人。基本上它是一个可点击的链接。然后你可以在你的网页的某个地方有另一个div标签

<div id="section">content</div>

在这种情况下,a链接将是可点击的,并将转到#section是什么,在这种情况下,它是我们称为section的div。

顺便说一句,我花了好几个小时才让它工作。在一些晦涩的评论区找到了解决方案。它是错误的,不会工作在一些标签。对身体不起作用。当我把它放在CSS文件中的html{}中时,它终于工作了。

要了解更全面的平滑滚动方法列表,请参阅我的回答在这里


你可以使用window.scroll()behavior: smoothtop设置为锚标记的偏移顶部,这确保锚标记将在视口的顶部。

document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', function (e) {
e.preventDefault();
var href = this.getAttribute("href");
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
//gets Element with an id of the link's href
//or an anchor tag with a name attribute of the href of the link without the #
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
});
//if you want to add the hash to window.location.hash
//you will need to use setTimeout to prevent losing the smooth scrolling behavior
//the following code will work for that purpose
/*setTimeout(function(){
window.location.hash = this.hash;
}, 2000); */
});
});

演示:

a, a:visited{
color: blue;
}


section{
margin: 500px 0px;
text-align: center;
}
<a href="#section1">Section 1</a>
<br/>
<a href="#section2">Section 2</a>
<br/>
<a href="#section3">Section 3</a>
<br/>
<a href="#section4">Section 4</a>
<section id="section1">
<b style="font-size: 2em;">Section 1</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>
<section>
<section id="section2">
<b style="font-size: 2em;">Section 2</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<section id="section3">
<b style="font-size: 2em;">Section 3</b>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<a style="margin: 500px 0px; color: initial;" name="section4">
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>
</a>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<script>
document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', function (e) {
e.preventDefault();
var href = this.getAttribute("href");
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
});
});
});
</script>

您可以将CSS属性scroll-behavior设置为smooth(大多数现代浏览器都支持),这样就不需要Javascript了。

html, body{
scroll-behavior: smooth;
}
a, a:visited{
color: blue;
}


section{
margin: 500px 0px;
text-align: center;
}
<a href="#section1">Section 1</a>
<br/>
<a href="#section2">Section 2</a>
<br/>
<a href="#section3">Section 3</a>
<br/>
<a href="#section4">Section 4</a>
<section id="section1">
<b style="font-size: 2em;">Section 1</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>
<section>
<section id="section2">
<b style="font-size: 2em;">Section 2</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<section id="section3">
<b style="font-size: 2em;">Section 3</b>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<a style="margin: 500px 0px; color: initial;" name="section4">
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>
</a>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.


Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.


Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.


Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.


Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>

有一种css方法可以使用scroll-behavior来做到这一点。添加以下属性。

    scroll-behavior: smooth;

就是这样。不需要JS。

a {
display: inline-block;
width: 50px;
text-decoration: none;
}
nav, scroll-container {
display: block;
margin: 0 auto;
text-align: center;
}
nav {
width: 339px;
padding: 5px;
border: 1px solid black;
}
scroll-container {
display: block;
width: 350px;
height: 200px;
overflow-y: scroll;
scroll-behavior: smooth;
}
scroll-page {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 5em;
}
<nav>
<a href="#page-1">1</a>
<a href="#page-2">2</a>
<a href="#page-3">3</a>
</nav>
<scroll-container>
<scroll-page id="page-1">1</scroll-page>
<scroll-page id="page-2">2</scroll-page>
<scroll-page id="page-3">3</scroll-page>
</scroll-container>

PS:请检查浏览器兼容性。

这里已经有很多很好的答案-但是他们都忽略了一个事实必须排除空锚。否则,只要单击空锚,这些脚本就会生成JavaScript错误。

在我看来,正确答案是这样的:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
event.preventDefault();


$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});

只有CSS

html {
scroll-behavior: smooth;
}

你只需要加上这个。现在你的内部链接滚动行为将是流畅的像一个流。

程序化:一些额外的和高级的东西

// Scroll to specific values
// window.scrollTo or window.scroll
window.scroll({
top: 1000,
left: 0,
behavior: 'smooth'
});


// Scroll certain amounts from current position
window.scrollBy({
top: 250, // could be negative value
left: 0,
behavior: 'smooth'
});


// Scroll to a certain element
document.getElementById('el').scrollIntoView({
behavior: 'smooth'
})

请注意:所有最新的浏览器(OperaChromeFirefox等)都支持此功能。

要详细了解,请阅读文章

要求jquery和动画锚标签与指定的名称而不是id,同时添加哈希到浏览器url。还修复了大多数jquery答案中#符号没有带转义反斜杠前缀的错误。返回按钮,不幸的是,不能正确地导航回以前的哈希链接…

$('a[href*=\\#]').click(function (event)
{
let hashValue = $(this).attr('href');
let name = hashValue.substring(1);
let target = $('[name="' + name + '"]');
$('html, body').animate({ scrollTop: target.offset().top }, 500);
event.preventDefault();
history.pushState(null, null, hashValue);
});

本机支持在哈希id滚动上平滑滚动。

html {
scroll-behavior: smooth;
}

你可以看看:https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

好吧,解决方案取决于问题的类型,我使用javascript动画方法按钮点击。我使用的代码从波纹链接导航栏

https://css-tricks.com/snippets/jquery/smooth-scrolling/

$(document).ready(function () {
$(".js--scroll-to-plans").click(function () {
$("body,html").animate(
{
scrollTop: $(".js--section-plans").offset().top,
},
1000
);
return false;
});


$(".js--scroll-to-start").click(function () {
$("body,html").animate(
{
scrollTop: $(".js--section-features").offset().top,
},
1000
);
return false;
});


$('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只是使用滚动行为:平滑的html标签就是这样

html{
scroll-behavior: smooth;
}