0

下面的平滑滚动脚本弄乱了我在 Safari 中的导航(锚标签不再起作用)。我是 Javascript 新手,谁能告诉我如何在这个脚本中检测 Safari 并阻止它在检测到 Safari 时执行?非常感谢!

// JavaScript Document
$(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}, 1300, function() { // scroll speed
            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 [];
  }

});
4

3 回答 3

0

参考:http ://api.jquery.com/jQuery.browser/ ,检测浏览器并仅在不是 safari 时执行脚本

于 2012-10-12T09:39:59.810 回答
0
var isSafari = navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") == -1;
if(!isSafari){
    // do your magic
}
于 2012-10-12T09:41:03.297 回答
0

也许是这样:

$(document).ready(function()
{
    if (navigator.appVersion.match(/WebKit/) && !navigator.vendor.match(/Google/))
    {
        return;
    }
    //rest of your code
});

如果您在 $(document).ready 回调之外有任何代码,则可以通过在脚本顶部编写以下代码来抛出错误来终止脚本:

if (navigator.appVersion.match(/WebKit/) && !navigator.vendor.match(/Google/))
{
    throw new Error('Safari not supported');
}
于 2012-10-12T09:47:17.873 回答