阻止Javascript在Safari中执行

时间:2012-10-12 09:36:37

标签: javascript safari smooth-scrolling

以下平滑滚动脚本会使我在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 [];
  }

});

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

var isSafari = navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") == -1;
if(!isSafari){
    // do your magic
}

答案 2 :(得分: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');
}