Detect phone/tablet/web client using javascript

后端 未结 4 1831
闹比i
闹比i 2020-12-17 01:08

I am trying to detect if the end user is on a phone, a tablet or a pc

I have been Googling for a while, apparently there are no easy solution.

Well I guess I

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 01:37

    Yes, you should not rely on resolution or orientation. But how about em-based media queries?

    In order to read the results of your media query with javascript, you could try adding a media query to your css to add invisible content to your page:

    @media all and (max-width: 45em) {
        body:after {
            content: 'smallscreen';
            display: none;
        }
    }
    

    Then read the content through javascript:

    var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
    

    Then determine what you want to load:

    if (size.indexOf('smallscreen') !=-1) {
        // Load some content for smaller screens.
    }
    

提交回复
热议问题