简体   繁体   English

在点击事件期间,JQuery scrollTo函数错误找不到滚动到某个div ID的方法

[英]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: 附加步骤:

  1. Add inline events to your navigation elements like this: 将内联事件添加到导航元素,如下所示:
<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 eventid ,让处理程序知道目标元素的id是什么。

  1. Handler function should be like this: 处理程序功能应该是这样的:
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: 补充笔记:

  • Don't put your function declarations inside $(document).ready . 不要将函数声明放在$(document).ready

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM