jQuery:仅针对 Safari

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6849086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:27:51  来源:igfitidea点击:

jQuery: Target ONLY Safari

jquerysafariconditional

提问by Dimitri Vorontzov

I'm using this bit of jQuery code to target Safari:

我正在使用这段 jQuery 代码来定位 Safari:

if ($.browser.safari) {
    $('#div1').css({'margin-top': '-22px'});
    $('#div2').css({'margin-top': '-17px'});
}

Oddly, it also targets Chrome (at least Mac version). What jQuery code can I use that would ignore Chrome and target only Safari?

奇怪的是,它还针对 Chrome(至少是 Mac 版本)。我可以使用哪些 jQuery 代码来忽略 Chrome 并仅针对 Safari?

I would be grateful for expert advice.

我将不胜感激专家的建议。

回答by Wulf

(Edit so that Chrome must not be in the user agent):

(编辑以便 Chrome 不能在用户代理中):

(Edit2 because Chrome for iOS has "CriOS" instead of "Chrome" in its user agent):

(Edit2 因为 iOS 版 Chrome 在其用户代理中有“CriOS”而不是“Chrome”):

if (
    navigator.userAgent.indexOf('Safari') != -1 && 
    navigator.userAgent.indexOf('Chrome') == -1 && 
    navigator.userAgent.indexOf('CriOS/') == -1
)  { 
   //i.e. apply safari class via jquery
}

P.S. You should consider using Feature Detectionto change your website according to what the current browser can do instead of checking for user agents, which you have to update regulary.

PS 您应该考虑使用功能检测根据当前浏览器可以执行的操作来更改您的网站,而不是检查您必须定期更新的用户代理。

回答by elslooo

if (navigator.userAgent.indexOf('Safari') && !navigator.userAgent.indexOf('Chrome')) {
    // Yep, it's Safari =)
}else {
    // Nope, it's another browser =(
}

回答by Joe Coder

Feature detection is preferred over browser sniffing, but I did find this solution on SO:

功能检测优于浏览器嗅探,但我确实在 SO 上找到了这个解决方案:

Detect Safari using jQuery

使用 jQuery 检测 Safari

回答by Dushyant Dagar

This Works Fine to know whether browser is Safari.

这可以很好地了解浏览器是否是 Safari。

if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
    alert('its safari');
}else{
    alert('its not safari');
}

回答by JSager

Try this:

尝试这个:

$.browser.safari = ( $.browser.safari && /chrome/.test(navigator.userAgent.toLowerCase()) ) ? false : true;

I like this a little better because you're setting the jQuery property properly, and can then use it elsewhere without constantly checking on the userAgent.

我更喜欢这个,因为您正确设置了 jQuery 属性,然后可以在其他地方使用它,而无需经常检查 userAgent。