jQuery 无法读取未定义的属性“顶部”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15907770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:59:45  来源:igfitidea点击:

Cannot read property 'top' of undefined

jqueryscroll

提问by bryanlewis

Trying to get the page to scroll to an anchor and I'm getting this error.

试图让页面滚动到一个锚点,我收到了这个错误。

Cannot read property 'top' of undefined

无法读取未定义的属性“顶部”

Right now I have my JS like the following...

现在我的 JS 如下所示...

//scroll to section process page
function scrollToAnchor(aid){
    var aTag = $("div[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

$("li.menu-item-141 a").click(function() {
   scrollToAnchor('#philosophy-page');
});

Here is my HTML...

这是我的 HTML...

<div class="container">
<div name="philosophy-page" id="philosophy-page">
    <div class="philosophy-heading">
        <h1>Philosophy</h1>
    </div><!-- /.philosophy-heading -->
</div><!-- /#philosophy-page -->
</div><!-- /.container -->

Any help would be great!

任何帮助都会很棒!

Thank you!

谢谢!

采纳答案by Adriano Carneiro

replace

代替

scrollToAnchor('#philosophy-page');

by

经过

scrollToAnchor('philosophy-page');

Remember you use the nameto find the aelement:

请记住,您使用name来查找a元素:

var aTag = $("div[name='"+ aid +"']");

jQuery cannot find an element named #philosophy-page

jQuery 找不到名为的元素 #philosophy-page

回答by Carl Sergile

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Best scroll to I have found. Found it on CSS Tricks: https://css-tricks.com/snippets/jquery/smooth-scrolling/

我找到的最好的滚动条。在 CSS Tricks 上找到它:https: //css-tricks.com/snippets/jquery/smooth-scrolling/

回答by Adil

Pass id without #as name does not #in it.

没有#名称的传递 id不在#其中。

Change

改变

 scrollToAnchor('#philosophy-page');

To

 scrollToAnchor('philosophy-page');