Easiest way to determine if user is on mobile device

流过昼夜 提交于 2020-01-12 13:51:08

问题


I'm showing a notification bar on my website, and frankly, it doesn't work well when its on a mobile device. I'd like to show the bar ONLY for desktop users.

What is the easiest way to determine if a user is on desktop or on mobile?


回答1:


Check this http://detectmobilebrowsers.com/

Work for Javascript, jQuery etc.




回答2:


A user agent check is the "easiest", though you could easily employ CSS3 media queries

Here is an example that checks iphone, android and blackberry; you could easily add other mobile browsers.

var is_mobile = !!navigator.userAgent.match(/iphone|android|blackberry/ig) || false;



回答3:


I find that it's best to use feature detection. Use Modernizr to detect if it's a touch device. You can do things like:

var mousedown = 'mousedown';

if (Modernizr.touch) {
    mousedown = 'touchstart';
}

$('.foo').on(mousedown, handleMouseDown);

And then use CSS Media Queries for handling screen width (and it's also easy to detect screen width with javascript). That way you can correctly handle touch devices with large screens, or non-touch devices with small screens.




回答4:


If you use modernizr. a "no-touch" class will be added to the element. You could hide the bar by default and add a css rule to show the bar if the "no-touch" class exists. Example:

default:

.bar{display:none;}

desktop:

.no-touch .bar{display:block;}



回答5:


If the user is on a mobile device this javascript 'if' will return true.

if (navigator.userAgent.indexOf('Mobile') !== -1) { ...

See also: https://deviceatlas.com/blog/list-of-user-agent-strings




回答6:


The easiest way to differentiate between touch and non-touch devices is using media queries.

1) CSS to target Mobile/Touch Devices can be written using media query,

  @media (hover: none), (pointer: coarse) {}

2) CSS to target Desktop/Non-Touch Devices (only) can be written using media query,

  @media not all and (pointer: coarse) {}

On Few latest mobile devices (Eg: IOS 10+, one plus etc.,.) hover is detected hence we use, the (2) to identify non-touch devices.



来源:https://stackoverflow.com/questions/15365352/easiest-way-to-determine-if-user-is-on-mobile-device

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