A check in JavaScript that returns whether I am on a smartphone? [duplicate]

痞子三分冷 提交于 2019-12-01 03:03:58

问题


I want to perform a check in one of my JavaScript functions that determines whether I am on a smartphone and then decide whether or not to run the function based on the results.

What is the best way to detect/check for a smartphone (or handheld device in general) in JavaScript?

e.g.

if (user is on a smartphone) {
//run this code if on a phone
} else {
//run this code if not on a phone
}

If there is not one definite method to check for a phone, then what are the best selection of checks I should to perform before deciding which code to run?

EDIT/UPDATE: The answers and comments on this similar post should give me something to go on - What is the best way to detect a mobile device in jQuery?


回答1:


Ye olde browser sniffing seems to be the solution

if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 ){
 // some code..
}



回答2:


You could try twitter bootstrap, http://twitter.github.com/bootstrap/scaffolding.html. In particular the Responsive design section.




回答3:


You can use the Categorizr JS library to test whether the user's device is a mobile phone, a tablet, a smart tv or a desktop. Categorizr uses user agent sniffing, so you should keep an eye out for updates to the script, as user agents tend to "evolve" over time.

Here's how you would use Categorizr to check if the user is on a smartphone, but not a smart TV, a desktop or a tablet:

if (categorizr.isMobile) {
    //run this code if on a phone
} else {
    //run this code if not on a phone
}


来源:https://stackoverflow.com/questions/11013778/a-check-in-javascript-that-returns-whether-i-am-on-a-smartphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!