[英]JQuery scrollTo function error can't find a way to scroll to a certain div ID during on click event
I'm trying to scroll to a certain section on on my website this section is marked with an ID and I want to do so using an animated jquery scroll on a click event. 我正在尝试滚动到我网站上的某个部分,此部分标有ID,我想在点击事件上使用动画jquery滚动。 This is my current code: 这是我目前的代码:
js header section js标题部分
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="index.js"></script>
Menu area 菜单区域
<li><a onclick="scrollTo()" href="#testimonials">Testimonials</a></li>
<li><a onclick="scrollTo()" href="#portfolio">Portfolio</a></li>
<li><a onclick="scrollTo()" href="#contact">Contact</a></li>
<li><a onclick="scrollTo()" href="#faq">FAQ</a></li>
Javascript file Javascript文件
$(document).ready(function() {
console.log("Test")
function scrollTo() {
console.log("Clicked!")
var elem = document.getElementById('testimonials');
console.log(elem)
elem.scrollTop = elem.scrollHeight;
window.scrollTo
}
})
See it here: codepen 在这里看到: codepen
Firstly : Don't use scrollTo
for your handler name. 首先:不要使用scrollTo
作为处理程序名称。 because scrollTo
is a function in js. 因为scrollTo
是js中的一个函数。
Additional Steps: 附加步骤:
<a onclick="scrollTo_(event,'testimonials')" href="#testimonials">Testimonials</a>
It will pass click event
and also an id
to let the handler know what's the target element's id. 它将传递click event
和id
,让处理程序知道目标元素的id是什么。
function scrollTo_(ev,id) {
ev.preventDefault();
$([document.documentElement, document.body]).animate({
scrollTop: $("#"+id).offset().top
}, 2000);
}
It's using preventDefault to prevent normal <a>
click behavior. 它使用preventDefault来阻止正常的<a>
点击行为。 and it use this answer ( how to animate scroll with jquery ) for animate scroll to element with jquery. 并使用此答案( 如何使用jquery动画滚动)以使用jquery动画滚动到元素。
Additional notes: 补充笔记:
$(document).ready
. 不要将函数声明放在$(document).ready
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.