【问题标题】:Detect both mobile device and orientation to add a code检测移动设备和方向以添加代码
【发布时间】:2026-01-03 01:40:01
【问题描述】:

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

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

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;}
}

但我不能将两者结合起来一起工作。

有没有一种方法可以让我在一个代码中同时检查移动设备和方向?

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

任何帮助表示赞赏。

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

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

    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{}
    

    谢谢。

    【讨论】:

      【解决方案2】:

      您可以使用 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)

      【讨论】:

        【解决方案3】:

        有一些纯 CSS 方法可以比 userAvent 嗅探更好地检测移动设备。换一种说法:永远不要进行 userAgent 嗅探。我保证你做错了。

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

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

        【讨论】:

          最近更新 更多