无法读取未定义的属性"top"

bry*_*wis 12 jquery scroll

试图让页面滚动到锚点,我收到此错误.

无法读取未定义的属性"top"

现在我有我的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');
});
Run Code Online (Sandbox Code Playgroud)

这是我的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 -->
Run Code Online (Sandbox Code Playgroud)

任何帮助都会很棒!

谢谢!

Adr*_*iro 12

更换

scrollToAnchor('#philosophy-page');
Run Code Online (Sandbox Code Playgroud)

通过

scrollToAnchor('philosophy-page');
Run Code Online (Sandbox Code Playgroud)

记住你用它name来找到a元素:

var aTag = $("div[name='"+ aid +"']");
Run Code Online (Sandbox Code Playgroud)

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


小智 5

$(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;
      }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

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