Uncaught TypeError: Cannot read property 'top' of undefined offset().top

喜你入骨 提交于 2020-03-06 04:43:06

问题


Hi there got this message here: Uncaught TypeError: Cannot read property 'top' of undefined

'scrollTop': $target.offset().top - 60

Code block:

$('.btn-circle-cover').on('click',function (e) {
    e.preventDefault();
    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
      'scrollTop': $target.offset().top - 60
  }, 2200, 'swing', function () {
      window.location.hash = target;
  });
});

回答1:


this.hash is not a valid because this will represent the <button> which will not have the href. Instead traverse to the parent element which has the href attribute using .parentNode and use .hash to get the hash of the href.

Example:

$('.btn-circle-cover').on('click', function(e) {
  e.preventDefault();
  var target = this,
    $target = $(target);
  $('html, body').stop().animate({
    'scrollTop': $target.offset().top - 60
  }, 2200, 'swing', function() {
    console.log('hash is: ', e.currentTarget.parentNode.hash)
    window.location.hash = e.currentTarget.parentNode.hash;
  });
});
body {
  height: 4000px;
}
button {
  margin-top: 3000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Down</p>
<a href="#hdsf">
  <button class="btn-circle-cover">Click here</button>
</a>


来源:https://stackoverflow.com/questions/40098804/uncaught-typeerror-cannot-read-property-top-of-undefined-offset-top

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!