为什么平滑的scrolling.js抛出“$ target.offset(...)是未定义的”错误?

时间:2013-07-24 12:24:44

标签: javascript jquery html runtime-error smooth-scrolling

我有一些javascript可以平滑滚动到任何点击的#anchor-id(this的改编)。对于某些网页,它会引发$target.offset(...) is undefined错误,并停止工作,我不明白为什么。

据我所知,我做了一些测试,似乎与页面的长度有关。保持所有变量相同,只改变内容量,发生错误(在完全相同的页面上)。

奇怪的是,我无法在jsfiddle上重现这种效果,它在那里的每一个长度都可以正常工作。有谁知道如何解决这个错误?可能是什么原因?


这是我正在使用的javascript(我链接到每个页面的底部,就在</body>标记之前,并在加载jquery 1.10.2之后立即链接到它:

$(document).ready(function() {
  function filterPath(string) {
  return string
 .replace(/^\//,'')
 .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
 .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');
  $('a[href*=#]').each(function() {
 var thisPath = filterPath(this.pathname) || locationPath;
 if (  locationPath == thisPath
 && (location.hostname == this.hostname || !this.hostname)
 && this.hash.replace(/#/,'') ) {
   var $target = $(this.hash), target = this.hash;
   if (target) {
  var targetOffset = $target.offset().top;
  $(this).click(function(event) {
    event.preventDefault();
    $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
   // commented line below because it adds a hash to the url and a history item
   // location.hash = target;
    });
  });
   }
 }
  });
  // use the first element that is "scrollable"
  function scrollableElement(els) {
 for (var i = 0, argLength = arguments.length; i <argLength; i++) {
   var el = arguments[i],
    $scrollElement = $(el);
   if ($scrollElement.scrollTop()> 0) {
  return el;
   } else {
  $scrollElement.scrollTop(1);
  var isScrollable = $scrollElement.scrollTop()> 0;
  $scrollElement.scrollTop(0);
  if (isScrollable) {
    return el;
  }
   }
 }
 return [];
  }
});

2 个答案:

答案 0 :(得分:5)

当哈希目标不存在时会发生这种情况。在HTML5中,有效的哈希目标只能用id编写。

所以这不起作用:

<a name="#hash">Hash</a>

但这会:

<a id="#hash">Hash</a>

由于使用name =“”不是HTML5,因此页面上不存在#hash,因此当您尝试使用它时引用它:

var $ target = $(this.hash) 它返回undefined。即使具有有效哈希目标的链接也不会平滑滚动,如果它们包含在无效的哈希目标之后也是如此。

答案 1 :(得分:0)

我知道这是一个老问题,但是最近我遇到了这个问题,建议的解决方案没有帮助。用于平滑滚动的所用脚本有错误。它仅检查链接是否链接到锚点。但是,如果定位目标实际上存在于当前页面上,则不会。所以这行

if (target) {

应该是

if ($target.length > 0) {