const goTagOne = function goTagOne(id) { const mao = document.getElementById(id); if (mao) { const pos = mao.offsetTop; function getScrollTop() { let scrollTop = 0; if (document.documentElement && document.documentElement.scrollTop) { scrollTop = document.documentElement.scrollTop; } else if (document.body) { scrollTop = document.body.scrollTop; } return scrollTop; } scrollTo(pos, 500); function scrollTo(y, duration) { // y:目标纵坐标,duration:时间(毫秒) const scrollTop = getScrollTop(); // 页面当前滚动距离 const distance = y - scrollTop; // 结果大于0,说明目标在下方,小于0,说明目标在上方 const scrollCount = duration / 10; // 10毫秒滚动一次,计算滚动次数 const everyDistance = distance / scrollCount; // 滚动距离除以滚动次数计算每次滚动距离 console.log(y, scrollTop); // 循环设置scrollBy事件,在duration之内,完成滚动效果 for (let index = 1; index <= scrollCount; index++) setTimeout(function () { window.scrollBy(0, everyDistance); }, 10 * index); } } };
|