jQuery Smooth Scroll to Top AND to Anchor by ID

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 07:35:21

问题


I'm finding answers for adding jQuery scroll to top OR scroll to anchors, but not really both integrated. So hope it's OK to ask here.

We have current jQuery function to add a scroll-to-top anchor for longer pages. It works fine.

// Add To Top Button functionality
jQuery(document).ready(function($){

    // Scroll (in pixels) after which the "To Top" link is shown
    var offset = 700,
    //Scroll (in pixels) after which the "back to top" link opacity is reduced
    offset_opacity = 1200,
    //Duration of the top scrolling animation (in ms)
    scroll_top_duration = 700,
    //Get the "To Top" link
    $back_to_top = $('.to-top');

//Visible or not "To Top" link
    $(window).scroll(function(){
    ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('top-is-visible') : $back_to_top.removeClass('top-is-visible top-fade-out');
    if( $(this).scrollTop() > offset_opacity ) { 
        $back_to_top.addClass('top-fade-out');
    }
});

//Smoothy scroll to top
$back_to_top.on('click', function(event){
    event.preventDefault();
    $('body,html').animate({
        scrollTop: 0 ,
        }, scroll_top_duration
    );
});

});
  • How would this be modified to also allow smooth scrolling to anchors on page, using an ID (e.g, <h2 id="anchor-name">), without conflicts?

TO CLARIFY: We need either a modification to the above script, or a complete new one that will not conflict with it, that will add smooth scrolling to any anchor link found in the existing HTML of a page (e.g., <a href="#any-anchor-link">). The JS should detect any anchor links and add the smooth scrolling functionality to it. We would not manually add specific anchor links to the JS.


回答1:


Extracted the scrolling logic into its own function, which accepts an element's id as an argument.

//Smoothy scroll to top
$back_to_top.on('click', function(event) {
    event.preventDefault();
    targetedScroll();
});

// example of smooth scroll to h2#anchor-name
$('#some-button').on('click', function(event) {
    event.preventDefault();
    targetedScroll('anchor-name');
});

// bind smooth scroll to any anchor on the page
$('a[href^="#"]').on('click', function(event) {
    event.preventDefault();
    targetedScroll($(this).attr('href').substr(1));
});

// scrolling function
function targetedScroll(id) {
    // scrollTop is either the top offset of the element whose id is passed, or 0
    var scrollTop = id ? $('#' + id).offset().top : 0;

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


来源:https://stackoverflow.com/questions/37931726/jquery-smooth-scroll-to-top-and-to-anchor-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!