问题描述
以某种方式我无法弄清楚如何使此“平滑滚动Jquery”脚本对我有用。
第一个console.log确实返回“测试”,而第二个在我单击链接后不返回任何内容。我正在通过Prepros开发Localhost,这可能与脚本无法正常工作有关吗?此外,代码不会返回任何错误。
jQuery Code Snippets: Smooth Scrolling
<script src="scripts/dist/jquery-3.3.1.js"></script>
var local = local || {};
local.Link = (function() {
var link = {};
console.log("Test");
function linkSmoothScroll() {
$('a[href*="#"]:not([href="#"])').click(function() {
console.log("Test-inside");
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length ? $target : $('[name=' + this.hash.slice(1) + ']');
if ($target.length) {
var baseMinScrollTime = 200,baseMaxScrollTime = 500;
var docHeight = $(document).height(),triggerTop = $(this).offset().top,targetTop = $target.offset().top;
var scrollProportion = (targetTop - triggerTop) / docHeight,relativeTime = ((baseMaxScrollTime - baseMinScrollTime) * scrollProportion) + baseMinScrollTime,// Create inverse relationship (quicker the further we scroll)
scrollTime = -1 * (1 - relativeTime);
$('html,body').animate({
scrollTop: targetTop - 10
},scrollTime);
return false;
}
}
});
}
linkSmoothScroll();
return self;
})();
解决方法
您可以简单地通过使滚动动画并使用其他CSS属性来做到这一点。
$("html,body").animate({ scrollTop: "0" }
html {
scroll-behavior: smooth;
}