2016-06-20 167 views
0

我找到了添加jQuery滚动到顶部或滚动到锚点的答案,但并非真的都集成了。所以希望可以在这里问问。jQuery平滑滚动到顶部并通过ID锚定

我们有当前的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(例如,<h2 id="anchor-name">),而不会发生冲突?

澄清:我们需要或者修改上面的脚本,或一个完整的新的,不会与之相冲突,这将平滑滚动添加到页面的现有的HTML中发现的任何锚链接(例如, ,<a href="#any-anchor-link">)。 JS应该检测任何锚链接并为其添加平滑滚动功能。我们不会手动向JS添加特定的锚链接。

+0

如何识别要滚动到的ID?在网页加载时解析网址?或者其他一些类型的输入(鼠标点击href)? – Nate

+0

是的,您的问题中没有足够的信息来确定要滚动到的位置。实际上这可能是困难的部分,滚动到它是微不足道的jquery – kirinthos

+0

为什么不使用真正的锚链接,并让jquery处理这些,所以回退是正常的行为? :) – Medda86

回答

0

将滚动逻辑提取到它自己的函数中,该函数接受元素的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); 
} 
+0

尝试在我的代码中用'// Smoothy scroll to top'替换掉所有内容,但没有运气。滚动到顶部仍然有效,但锚链接不平滑。这是否需要将特定的锚定添加到JS中,还是将其从页面上的HTML拾取?!?对不起,JS不流利。我试着添加一个当前的锚点ID来替换你的'锚点名称'作为测试,但是这也不起作用。需要它在任何页面上选择现有的锚链接(例如,