jQuery Smooth to Scroll to Top AND to Anchor by ID

我找到了将jQuery滚动添加到顶部或滚动到锚点的答案,但实际上并没有集成。 所以希望可以在这里问一下。

我们有当前的jQuery函数来为较长的页面添加滚动到顶部的锚点。 它工作正常。

// 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 ); }); }); 
  • 如何修改以允许使用ID(例如,

    )平滑滚动到页面上的

    ,而不会发生冲突?

要澄清:我们需要修改上面的脚本,或者一个不会与它发生冲突的全新脚本,它将平滑滚动到页面现有HTML中找到的任何锚链接(例如, )。 JS应检测任何锚链接并为其添加平滑滚动function。 我们不会手动向JS添加特定的锚链接。

将滚动逻辑提取到自己的函数中,该函数接受元素的id作为参数。

 //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); }