How to use a different stylesheet for iphone or android?

前端 未结 5 2204
甜味超标
甜味超标 2021-01-15 11:07

I\'m trying to make a page where some elements will be visible only for android and iphone. I was thinking of using simple css properties to hide the elements e.g.:

5条回答
  •  清歌不尽
    2021-01-15 11:51

    My code differs from the other solutions in that you don't apply styles or read the DOM dynamically — you detect the device, set a class, and let CSS do the rest. This means you can run the script immediately (without knowing how many images or whatnot are needed), and then extend your HTML and CSS as you see fit. It's also far more performant, and doesn't require any libraries.

    First of all, change your CSS to match the following:

    img{
      display:none;
    }
    
    html.other .other{
      display:inline;
    }
    
    html.iphone  .iphone {
      display:inline;
    }
    
    html.ipad    .ipad   {
      display:inline;
    }
    
    html.android .android{
      display:inline;
    }
    

    Basically, we're relying on a class on the HTML to infer what the device is. If you want generic iOS, then you can add another class to your images and add the following:

    html.ipad    .ios,
    html.iphone  .ios    {
      display:inline;
    }
    

    Then we run some script to infer that and apply it based on the user agent string (inferrable only I'm afraid, this is the best we can do!):

    void function setUAclass(){
      var ua      = navigator.userAgent.toLowerCase();
      var agent   = 'other';
      var classes = [
        'ipad',
        'iphone',
        'android'
      ];
    
      for(var i = 0, l = classes.length; i < l; ++i){
        if(ua.indexOf(classes[i]) >= 0){
          agent = classes[i]
        }
      }
    
      document.lastElement.className += ' ' + agent;
    }();
    

    You can run this without jQuery, at any point in the document. There's no need to wait for DOM ready because document.lastElement and navigator.userAgent are always readily available by the time any script can execute.

提交回复
热议问题