我想构建一个 webAPP 并显示不同的内容,当
- 用户通过他们的 safari 浏览器打开 webAPP 或
- 当他们从主屏幕通过网络剪辑打开 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’”。
- 要么移动
<script>
挡住 body 的尽头 更好的是,使用 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/