确定JS中元素的位置-移动与桌面



我在JS中做了一个滚动函数,它可以确定元素在页面上的位置,点击标题中的一个锚标记,它就会带你进入页面的特定部分。它在桌面上运行得很好,尽管在手机上运行不正常。比方说,当我点击Gallery时,它会把我带到Gallery部分的中间,尽管JS在桌面和手机上读取的位置相同。有什么办法解决这个问题吗?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<header>
<ul class="nav-left">
<li><a class="anchor-About" href="#">Über mich</a></li>
<li><a class="anchor-Gallery" href="#">Galerie</a></li>
</ul>
<a class="anchor-Home" href="#"> <img src="styles/Images/logo.png" id="logo" alt=""></a>
<ul class="nav-right">
<li><a class="anchor-Contact" href="#">Kontakt</a></li>
</ul>
<section id="About"></section>
<section id="Gallery"></section>
<section id="Contact"></section>
</header>
</body>
</html>
section {
height: 100vh;
}
#About {
background-color: red
}
#Gallery {
background-color: black
}
#Contact {
background-color: blue
}
const sectionAboutNav = document.querySelector('.anchor-About');
const sectionGalleryNav = document.querySelector('.anchor-Gallery');
const sectionContactNav = document.querySelector('.anchor-Contact');
const sectionAbout = document.getElementById('About')
const sectionGallery = document.getElementById('Gallery')
const sectionContact = document.getElementById('Contact')
const sectionAboutPosition = sectionAbout.getBoundingClientRect().top + sectionAbout.ownerDocument.defaultView.pageYOffset;
const sectionGalleryPosition = sectionGallery.getBoundingClientRect().top + sectionGallery.ownerDocument.defaultView.pageYOffset;
const sectionContactPosition = sectionContact.getBoundingClientRect().top + sectionContact.ownerDocument.defaultView.pageYOffset;
function smoothScroll(duration, sectionPosition){
const trgtPosition = sectionPosition;
const startPosition = window.pageYOffset;
const distance = trgtPosition - startPosition;
let startTime = null;

function animationScroll(currentTime){
if(startTime === null) startTime = currentTime;
const timeElapse = currentTime - startTime; 
const run = ease(timeElapse, startPosition, distance, duration);
window.scrollTo(0, run);
if(timeElapse < duration){requestAnimationFrame(animationScroll)};
}
function ease (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
requestAnimationFrame(animationScroll);
}
sectionAboutNav.addEventListener('click', function(e){
e.preventDefault();
smoothScroll(500, sectionAboutPosition);
console.log(sectionAboutPosition + 'this is position of about me section')
})
sectionGalleryNav.addEventListener('click', function(e){
e.preventDefault();
smoothScroll(500, sectionGalleryPosition);
console.log(sectionGalleryPosition + 'this is a position of gallery section')
})
sectionContactNav.addEventListener('click', function(e){
e.preventDefault();
smoothScroll(500, sectionContactPosition);
console.log(sectionContactPosition + 'this is a position of contact section')
})

最有可能的原因是,您不是在单击按钮的那一刻计算偏移顶部(常量«section[*]Position»(,而是在加载脚本的那一时刻。

要解决此问题,请将上述常量传输到«click»事件侦听器。

最新更新