iphone - 如果用户在 iPhone 和 window.navigator.standalone == true 上,则在 userAgent 时更改 css 显示

标签 iphone html css user-agent getelementbyid

我想构建一个 webAPP 并显示不同的内容,当

  1. 用户通过他们的 safari 浏览器打开 webAPP 或
  2. 当他们从主屏幕通过网络剪辑打开 webAPP 时

检测有效 - 我用 document.write 检查它 - 但 CSS 显示属性没有改变。 我做错了什么?

在此先致谢!

<html>
<head>
<meta name="apple-mobile-web-app-capable" content="yes">
<script type="text/javascript">
if (window.navigator.userAgent.indexOf('iPhone') != -1) {
    if (window.navigator.standalone == true) {
        // document.write('<p>homescreen<\/p>');
        document.getElementById("homescreen").style.display = 'block';
    }else{
        // document.write('<p>safari<\/p>');
        document.getElementById("safari").style.display = 'block';
    }
}else{
        // document.write('<p>no iOS<\/p>');
        document.getElementById("ios").style.display = 'block';
}
</script>
</head>
<body>

<div id="homescreen" style="display:none;">
you opened it from the homescreen
</div>

<div id="safari" style="display:none;">
you opened it from safari
</div>


<div id="ios" style="display:none;">
you have no iOS
</div>



</body>
</html>

最佳答案

<script>在加载 DOM 之前进行评估,因此 document.getElementById("xx")返回 undefined .检查您的 javascript 错误控制台,可能会出现如下错误:“未捕获的 TypeError:无法读取 null 的属性‘style’”。

  1. 要么移动<script>挡住 body 的尽头
  2. 更好的是,使用 jQuery 和类似的东西,参见 http://api.jquery.com/ready/

    $(function() {
      if (window.navigator.userAgent.indexOf('iPhone') != -1) {
        if (window.navigator.standalone) {
          $('#homescreen').show();          
        }else{
          $('#safari').show();
        }
      }else{
        $("#ios").show();
      }
    });
    

或者更好、更灵活的替代方法是将类附加到 <body>元素,那么您可以使用 CSS 轻松显示/隐藏任何内容。

$(function() {
   if (window.navigator.standalone) {
     $('body').addClass('standalone');
   }
});

然后在 CSS 中,所有部分都可以根据这些标识符轻松显示/隐藏。

.someContent { display: none; }
body.standalone .someContent { display: block; }

对于移动选择器 (iPhone),您甚至可以避免使用 JS userAgent 开关(仅供引用,您的 indexOf 与 iPad 或 iPod Touch 不匹配)并且更好地依赖 CSS 媒体查询,例如 @media only screen and (max-device-width: 480px) (这个用于 iPhone 横向和纵​​向)。

关于iphone - 如果用户在 iPhone 和 window.navigator.standalone == true 上,则在 userAgent 时更改 css 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9940395/

相关文章:

iphone - 有关如何手动安装 XMPPFramework 的最新说明?

android - OpenGL ES 2.0 指定位置属性 vec3 或 vec4

javascript - HTML:如何从下拉列表中删除 "None"

javascript - 修改元素选择部分的光标属性

html - HTML 中的时事通讯是否应该具有 "table-based"布局?

iphone - 如何检查 iPhone 5 是否运行 iOS 7?

iphone - 编辑和删除现有的 EKEvent?

javascript - 是否可以禁用网页上的查找功能,而不仅仅是 CTRL + F?

javascript - 如何在 React 的嵌套组件场景中使页脚居中对齐

javascript - 不同网站上的列表看起来不同