我有一个滚动到元素的脚本。当你点击 <a href>
,然后滚动到该元素。
脚本有效,但现在是问题所在。脚本滚动到元素。但我仍然希望脚本滚动到元素 + 100 像素以下。
我怎样才能在这个脚本中做到这一点?
感谢您的帮助!
脚本:
window.smoothScroll = function () {
if (document.querySelectorAll === void 0 || window.pageYOffset === void 0 || history.pushState === void 0) {
return
}
var e = function (e) {
if (e.nodeName === "HTML") return -window.pageYOffset;
return e.getBoundingClientRect().top + window.pageYOffset
};
var t = function (e) {
return e < .5 ? 4 * e * e * e : (e - 1) * (2 * e - 2) * (2 * e - 2) + 1
};
var n = function (e, n, r, i) {
if (r > i) return n;
return e + (n - e) * t(r / i)
};
var r = function (t, r, i) {
r = r || 500;
var s = window.pageYOffset;
if (typeof t === "number") {
var o = parseInt(t)
} else {
var o = e(t)
}
var u = Date.now();
var a = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function (e) {
window.setTimeout(e, 15)
};
var f = function () {
var e = Date.now() - u;
window.scroll(0, n(s, o, e, r));
if (e > r) {
if (typeof i === "function") {
i(t)
}
} else {
a(f)
}
};
f()
};
var i = function (e) {
e.preventDefault();
if (location.hash !== this.hash) window.history.pushState(null, null, this.hash);
r(document.getElementById(this.hash.substring(1)), 500, function (e) {
location.replace("#" + e.id)
})
};
document.addEventListener("DOMContentLoaded", function () {
var e = document.querySelectorAll('a[href^="#"]'),
t;
for (var n = e.length; t = e[--n];) {
t.addEventListener("click", i, false)
}
});
return r
}()
最佳答案
您将此标记为“jQuery”,所以我假设您会接受 jQuery 解决方案: 它更简单、更短。
你没有提供你的 html 标记,所以我不知道你的页面上发生了什么,但你可以这样做:
$("#button").click(function() {
$('body').animate({
scrollTop: $("#div7").offset().top +100
}, 1000);
});
这里有一个例子:Fiddle
关于javascript - 滚动到一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23286880/