单击锚点时,将属性“ data-target”传递给我的 target 变量。在滚动功能中,我在参数中传递了目标,并且一切正常。我的问题是控制台记录了一个错误,该错误显示目标在此行中返回空值:
var targetPosition = target.offsetTop;
谁能解释为什么会这样?
var anchors = document.querySelectorAll('a[href^="#"]');
var headerHeight = document.querySelector('header').offsetHeight;
for (var i = 0; i < anchors.length; i++) {
anchors[i].addEventListener('click', function(event) {
event.preventDefault();
var anchor_location = this.getAttribute('data-target');
// Find the element with ID that matches data-target value.
var target = document.querySelector(anchor_location);
scroll(target, headerHeight);
})
}
function scroll(target, headerHeight) {
var start = null;
var duration = 1100; //d
var targetPosition = target.offsetTop;
var startPosition = window.pageYOffset; //b
var distance = targetPosition - startPosition - headerHeight; //c
console.log(distance);
window.requestAnimationFrame(step);
function step(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start; //t
// window.scrollTo(0, distance*(progress/duration) + startPosition);
window.scrollTo(0, quintic(progress, startPosition, distance, duration));
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
}
// http://www.gizma.com/easing/ [easing equations]
function quintic (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t*t*t*t + b;
t -= 2;
return c/2*(t*t*t*t*t + 2) + b;
};