【发布时间】:2016-07-30 01:23:35
【问题描述】:
这是对之前在此处回答的问题的扩展:See Prevoius Question
我有一点 jQuery,它既可以平滑滚动到顶部功能,又可以平滑滚动到页面上的任何锚点。
现在,我只需要为锚滚动添加一个偏移量 (110px) 以解决固定标题,而不会弄乱滚动到顶部的功能。
这是现有的代码:
// Add To Top Button + Smooth Scroll to Anchors 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');
}
});
//Smooth 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);
}
});
【问题讨论】:
-
在我的网站上,我只是给导航栏下方页面上的第一个元素一个锚点。这样你仍然可以使用偏移量。
-
嗨,我不确定我是否在此处关注您添加额外的锚点或“仍在使用偏移量”(我还没有设置偏移量,这就是我希望了解如何添加的内容) .
标签: javascript jquery smooth-scrolling