How to target Safari for Mac only?

后端 未结 10 1893
终归单人心
终归单人心 2020-12-05 05:39

Hi I\'ve cross browser fixed a site on all thinkable PC browsers, including Safari. Now my smart ass designer sent me a screen shot of the whole layout collapsing on mac. I

10条回答
  •  一个人的身影
    2020-12-05 06:18

    Building off of @Tim Abell's solution, you can use a similar approach to get classes for all of the major platforms and browsers for broader detection and flexibility.

    This snippet will add a class for the browser name and another for the platform name to the element. So, for example, Safari on Mac would end up being .

    Javascript/jQuery

    //Search for keywords within the user agent string.  When a match is found, add a corresponding class to the html element and return.  (Inspired by http://stackoverflow.com/a/10137912/114558)
    function addUserAgentClass(keywords) {
      for(var i = 0; i < keywords.length; i++) {
        if(navigator.userAgent.indexOf(keywords[i]) != -1) {
          $("html").addClass(keywords[i].toLowerCase());
          return; //Once we find and process a matching keyword, return to prevent less "specific" classes from being added
        }
      }
    }
    
    addUserAgentClass(["Chrome", "Firefox", "MSIE", "Safari", "Opera", "Mozilla"]); //Browsers listed generally from most-specific to least-specific
    addUserAgentClass(["Android", "iPhone", "iPad", "Linux", "Mac", "Windows"]); //Platforms, also in order of specificity
    

    With this approach, you can do things like:

    CSS

    .safari { /* Safari only */ }
    .mac { /* Mac only */ }
    .safari.mac { /* Safari Mac */ }
    html:not(.safari) { /* All browsers except for Safari */ }
    html:not(.safari.mac) { /* All browsers except for Safari Mac */ }
    

提交回复
热议问题