Browser & OS as body class

前端 未结 2 985
情歌与酒
情歌与酒 2021-01-06 05:41

I would like to have the OS and the Browser in the body class. I need that for pixelperfect styling, because the fonts do not behave the same way in different OS / Browser c

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 06:11

    You could use regex, but it wouldn't make it any prettier.

    Basically, scanning user agent strings for browser/os/version is never going to be beautiful.

    Here is something a little prettier with jQuery...

    // Add some classes to body for CSS hooks
    
    // Get browser
    $.each($.browser, function(i) {
        $('body').addClass(i);
        return false;  
    });
    
    
    // Get OS
    var os = [
        'iphone',
        'ipad',
        'windows',
        'mac',
        'linux'
    ];
    
    var match = navigator.appVersion.toLowerCase().match(new RegExp(os.join('|')));
    if (match) {
        $('body').addClass(match[0]);
    };
    

    This doesn't quite give you the same classes as above, but enough to differentiate different OS and browser.

    For example, you could target Firefox on Windows with...

    body.windows.mozilla {
        background: blue;
    }
    

    See it!

    Or use a plugin.

提交回复
热议问题