我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。
我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。
我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。
我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。
我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。
我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。
当前回答
我通常发现,检查只在移动视图中可见的特定元素(比如汉堡图标)的可见性这一更简单的方法效果很好,而且比依赖非常复杂的正则表达式安全得多。这将很难测试100%的工作。
function isHidden(el) {
return (el.offsetParent === null);
}
其他回答
UserAgent不是100%可靠的。
window.navigator.maxTouchPoints > 1;
这就够了!它排除了浏览器开发控制台中的电话模拟器。这对我来说很重要。
为了增加额外的控制层,我使用HTML5存储来检测它是使用移动存储还是桌面存储。如果浏览器不支持存储,我有一个移动浏览器名称数组,并将用户代理与数组中的浏览器进行比较。
这很简单。函数如下:
// Used to detect whether the users browser is an mobile browser
function isMobile() {
///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>
if (sessionStorage.desktop) // desktop storage
return false;
else if (localStorage.mobile) // mobile storage
return true;
// alternative
var mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile'];
for (var i in mobile) if (navigator.userAgent.toLowerCase().indexOf(mobile[i].toLowerCase()) > 0) return true;
// nothing found.. assume desktop
return false;
}
不要使用这种方法作为窗口。朝向现在已弃用!!
function isMobile() {
return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
};
啊,是的,这个古老的问题……
这取决于你对知识的反应。
1. 你想改变UI,让它适合不同的屏幕尺寸吗?
使用媒体查询。
2. 你想显示/隐藏东西或改变基于鼠标和触摸的功能吗?
上面的答案可以解决问题,但也可能出现用户同时拥有两个选项并切换的情况。在这种情况下,当你检测到鼠标或触摸事件时,你可以切换一些JS变量和/或向文档主体添加一个类
window.addEventListener("mousemove", function () {
isTouch = false;
document.body.classList.add("canHover");
});
window.addEventListener("touchstart", function () {
isTouch = true;
document.body.classList.remove("canHover");
});
body.canHover #aButtonOrSomething:hover {
//css attributes
}
document
.getElementById("aButtonOrSomething")
.addEventListener("mouseover", showTooltip);
document
.getElementById("aButtonOrSomething")
.addEventListener("click", function () {
if (isTouch) showTooltip();
});
3.你想做一些具体的事情,知道他们有什么设备吗?
使用公认的答案。
使用window.screen怎么样?宽度”?
if (window.screen.width < 800) {
// do something
}
or
if($(window).width() < 800) {
//do something
}
我想这是最好的方法,因为每天都有新的移动设备!
(虽然我认为旧的浏览器不支持它,但试试看吧:))