繁体   English   中英

检测移动设备和方向以添加代码

[英]Detect both mobile device and orientation to add a code

如果用户在移动设备上并且方向是纵向的,我想向他们显示文本。

为了检测移动设备,我正在使用这个脚本:

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
  document.write("mobile");
}else{
  document.write("not mobile");
}

对于纵向模式,我使用的是这个 CSS:

@media (orientation: portrait) {
    .land-msg {display: block;}
}

但我不能将两者结合起来相互合作。

你有办法让我在一个代码中同时检查移动设备和方向吗?

媒体屏幕大小不起作用,因为我不希望它在桌面浏览器调整大小时显示。

任何帮助表示赞赏。

我已使用以下代码使其工作:

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
    if(window.innerHeight > window.innerWidth){
        jQuery(".land-msg").css("display", "block");
    }
}else{}

谢谢你。

您可以使用 matchMedia 来检测方向(最小/最大宽度等)

 const isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) function matchMediaHandler(query) { if (query.matches) { // If media query matches (portrait) document.body.style.backgroundColor = "orange" document.body.innerText = isMobile? 'Mobile Portrait': 'Desktop Portrait' } else { document.body.style.backgroundColor = "yellowgreen" document.body.innerText = isMobile? 'Mobile Landscape': 'Desktop Landscape' } } // orientation query const orientation = matchMedia("(orientation: portrait)") // add listener orientation.addListener(matchMediaHandler) // trigger on load matchMediaHandler(orientation)

有纯粹的 CSS 方法可以以比 userAvent 嗅探更好的方式检测移动设备。 换句话说:永远不要进行 userAgent 嗅探。 我 promise 你做错了。

/* smartphones, touchscreens */
@media (hover: none) and (pointer: coarse) and (orientation: portrait) {
    /* ... */
}

部分内容取自这里: https://ferie.medium.com/detect-a-touch-device-with-only-css-9f8e30fa1134

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM