简体   繁体   中英

Prevent Javascript from executing in Safari

The following smooth scrolling script messes up my navigation in Safari (anchor tags don't work anymore). I'm a Javascript newbie, could anyone tell me how to detect Safari in this script and prevent it from executing when it detects Safari? Many thanks!

// 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 [];
  }

});

请参阅: http : //api.jquery.com/jQuery.browser/ ,以检测浏览器并仅在非Safari浏览器时执行脚本

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

Perhaps this:

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

if you have any code outside the $(document).ready callback, you could kill the script by throwing an error, by writing this at the top of your script(s):

if (navigator.appVersion.match(/WebKit/) && !navigator.vendor.match(/Google/))
{
    throw new Error('Safari not supported');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM