未捕获的TypeError:无法读取属性' offset'未定义的

时间:2018-05-24 15:45:25

标签: javascript jquery

我收到未捕获的TypeError:无法读取属性' offset'未定义的

在此之前我得到了相同的例外情况,其中包括' top'从同一块。我现在以一种方式修复它,我收到错误' offset'。

这是我的代码。

var ssSmoothScroll = function() {

    $('.smoothscroll').on('click', function (e) {
        if (this.hash !== "" && this.pathname == window.location.pathname) {
        var target = this.hash;
        // $target    = $(target);


        e.preventDefault();
        e.stopPropagation();

        var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top :)
            if (target != "#top") { //If the target is not "#top", then calculate topOffset 
            var topOffset = $(target).offset().top;
            }
        }
        else{
                var target = this.hash,
                $target    = $(target);

                e.preventDefault();
                e.stopPropagation();

        }
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, cfg.scrollDuration, 'swing', function () {
            window.location.hash = target;
        });
    });
};

感谢任何帮助:)

2 个答案:

答案 0 :(得分:0)

因为你在else语句中定义了$target所以如果它没有进入else,那么它是未定义的。

您需要在其他

之外设置$target
if (target != "#top") {
  // you do not set it here
  ...
else{
  var target = this.hash,  // <-- not sure why you are declaring target again....
  $target    = $(target); // you set it here
  ...
}

答案 1 :(得分:0)

请尝试使用此代码,我认为这可行

var ssSmoothScroll = function() {
  $(".smoothscroll").on("click", function(e) {
    if (this.hash !== "" && this.pathname == window.location.pathname) {
      var target = this.hash,
        $target = $(target);
      // $target    = $(target);

      e.preventDefault();
      e.stopPropagation();

      var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top :)
      if (target != "#top") {
        //If the target is not "#top", then calculate topOffset
        topOffset = $(target).offset().top;
      }
      $("html, body")
        .stop()
        .animate(
          {
            scrollTop: $target.offset().top
          },
          cfg.scrollDuration,
          "swing",
          function() {
            window.location.hash = target;
          }
        );
    }
  });
};