问题
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