HTML5: Detecting if you're on mobile or pc with javascript?

This question already has an answer here:

  • What is the best way to detect a mobile device in jQuery? 49 answers

  • I was looking into this a few years back. In short, you can't do this with 100% reliability. There seem to be 2 approaches commonly used to provide a 'best-guess':

    1. User Agent Detection This is where you check what the client is claiming to be. eg

    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
        // is mobile..
    }
    

    It's not perfect, since I believe it is fairly easy for this property to be altered accidentally or otherwise. Plus it is highly unlikely that this list will still be accurate in 2 years' / 2 weeks' / 2 days' time!

    2. Using Screen Width As you can imagine, a more pragmatic approach - allows you to cater to the known physical capability of the client. eg

    if( screen.width <= 480 ) {     
        // is mobile.. 
    }
    

    However this is not ideal either, since higher and higher pixel densities in modern devices give you a misleading result: appearing that you have more 'room' than you actually do.

    If anyone has any better ideas to robustly discern between desktop and device, please comment! :)

    链接地址: http://www.djcxy.com/p/84050.html

    上一篇: 检测移动设备

    下一篇: HTML5:检测您是否在手机或电脑上使用JavaScript?