[英]scrollIntoView in not working, why? and how to fixed?
How can I make this code work?我怎样才能使这段代码工作? I'm getting errors我收到错误
//scroll to section this part is to get all the //scroll to section 这部分是获取所有的
const linkes = document.querySelectorAll('a')
linkes.forEach(link => {
link.addEventListener('click', toSection())
})
this part is to build the function for scrollIntoView这部分是为 scrollIntoView 构建 function
function toSection() {
sections.forEach(section => {
const sectionsIds = section.id
})
sectionsIds.scrollIntoView();
}
You can do it like this你可以这样做
<a data-myattr="myScrollSection1">to section 1</a>
<a data-myattr="myScrollSection2">to section 2</a>
<div id="myScrollSection1">Section1</div>
<div id="myScrollSection2">Section2</div>
<script>
const links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", (e) => {
myId = e.target.dataset.myattr;
console.log(myId);
document.getElementById(myId).scrollIntoView();
});
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.