如何在特定ID上平滑滚动导航到另一个页面?

Mus*_*hmy 2 html javascript css html5 css3

我有一个多页面的网站..所以我需要一个代码,用于在加载到另一个页面上的特定ID或部分后平滑滚动导航到另一个页面

例如在导航栏中我有多个因此我将使一个页面包含来自导航栏的4个链接..所以我需要当我点击导航栏中的链接导航我到包含此链接的页面并顺利向下滚动到该部分包含此链接我点击它

我没有使用html但没有平滑滚动..我只需点击导航栏中的链接,它就会导航到包含此链接信息的指定部分.在另一页

我不知道我的问题是否足够清楚,但我希望如此

小智 11

现代浏览器检测网址中的哈希值,然后自动打开该部分.因此,如果要平滑滚动到该部分,首先需要将滚动位置重置为0,然后添加平滑滚动.

添加以下内容 script

// direct browser to top right away
if (window.location.hash)
    scroll(0,0);
// takes care of some browsers issue
setTimeout(function(){scroll(0,0);},1);
Run Code Online (Sandbox Code Playgroud)

现在,尝试从其他页面访问锚点,您会注意到浏览器会将您带到页面顶部而不会滚动到锚点元素.

现在,添加平滑滚动:

$(function(){
//your current click function
$('.scroll').on('click',function(e){
    e.preventDefault();
    $('html,body').animate({
        scrollTop:$($(this).attr('href')).offset().top + 'px'
    },1000,'swing');
});

// if we have anchor on the url (calling from other page)
if(window.location.hash){
    // smooth scroll to the anchor id
    $('html,body').animate({
        scrollTop:$(window.location.hash).offset().top + 'px'
        },1000,'swing');
    }
});
Run Code Online (Sandbox Code Playgroud)

它现在将完美地运作.您将被带到其他页面中的锚元素,并顺利滚动到该部分.

完整代码:

// direct browser to top right away
if (window.location.hash)
    scroll(0,0);
// takes care of some browsers issue
setTimeout(function(){scroll(0,0);},1);

$(function(){
//your current click function
$('.scroll').on('click',function(e){
    e.preventDefault();
    $('html,body').animate({
        scrollTop:$($(this).attr('href')).offset().top + 'px'
    },1000,'swing');
});

// if we have anchor on the url (calling from other page)
if(window.location.hash){
    // smooth scroll to the anchor id
    $('html,body').animate({
        scrollTop:$(window.location.hash).offset().top + 'px'
        },1000,'swing');
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 5

在你的 CSS 文件中只需添加 -

html {
    scroll-behavior: smooth;
} 
Run Code Online (Sandbox Code Playgroud)

并将 href 中的 ID 指定为

href="file_where_the_element_is.html#ID_of_the_element

例如:

<a href="index.html#contentID>
Run Code Online (Sandbox Code Playgroud)

就这么简单!!!无需 JS、JQuery。仅 CSS 和 HTML