通过JS自动隐藏手机浏览器的地址栏

来源:互联网 发布:算法1mints.txt 编辑:程序博客网 时间:2024/06/06 18:04

       大家通过手机自带浏览器打开百度、淘宝,在首页加载完毕后,会自动隐藏页面上方的地址栏,加之这些网站针对手机浏览器做了优化,乍看之下,还真难区分这是WEB APP还是Native App,如下左侧图片为通过safari打开淘宝网的首页,要不是因为底下的浏览器工具栏,还真像Native App。实际上它是有地址的,向下拖动就会看到地址栏,如下右侧图片。

如何才能实现将浏览器地址栏隐藏呢?百度一下,有很多资料,很简单,主要利用window.scrollTo()方法,将当前页面在屏幕上向上滚动,造成地址栏超出视野范围,如下:

<script>window.onload=function(){setTimeout(function() {window.scrollTo(0, 1)}, 0);};</script>
但若你做一个简单页面,比如只有一句话,加上如上脚本,你会悲摧的发现,地址栏就是不自动隐藏;难道window.scrollTo()方法在这个浏览器不生效?

但是若你网页内容比较多,超过屏幕高度时,却会自动隐藏地址栏;

如何解决在内容较少时,同样隐藏地址栏呢?需在滚动之前程序动态设置一下body的高度,增加如下代码:

if(document.documentElement.scrollHeight <= document.documentElement.clientHeight) {bodyTag = document.getElementsByTagName('body')[0];bodyTag.style.height = document.documentElement.clientWidth / screen.width * screen.height + 'px';}

如下为一个页面示例(默认隐藏地址栏),右图为下拉后看到地址栏的截图:















如上截图的完整源码如下:

<!DOCTYPE html> <html> <head> <meta charset=utf-8 /><meta name="viewport" content="width=device-width, initial-scale=1,"> <title>我是个网页,但不显示滚动条</title> <script>window.onload=function(){if(document.documentElement.scrollHeight <= document.documentElement.clientHeight) {bodyTag = document.getElementsByTagName('body')[0];bodyTag.style.height = document.documentElement.clientWidth / screen.width * screen.height + 'px';}setTimeout(function() {window.scrollTo(0, 1)}, 0);};</script><style>/*输入框圆角显示*/input {    background:#fff; border: 1px solid #080;    padding:5px;    -webkit-border-radius:5px;}/* button ---------------------------------------------- */.button {display: inline-block;zoom: 1; /* zoom and *display = ie7 hack for display:inline-block */*display: inline;vertical-align: baseline;margin: 0 2px;outline: none;cursor: pointer;text-align: center;text-decoration: none;font: 14px/100% Arial, Helvetica, sans-serif;padding: .5em 2em .55em;text-shadow: 0 1px 1px rgba(0,0,0,.3);-webkit-border-radius: .5em; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);}/* green */.green {color: #e8f0de;border: solid 1px #538312;background: #64991e;background: -webkit-gradient(linear, left top, left bottom, from(#7db72f), to(#4e7d0e));}</style></head> <body style="background: #ededed;"> <div style="padding-top:40%;padding-left:20%">帐号:<input type="text"><br/>密码:<input type="text"><br/><div><div style="padding-top:5%;padding-left:23%"><input type="button" class="button green" value="登录"></div></body></html>

如上按钮的效果,参考自:http://www.webdesignerwall.com/demo/css-buttons.html


要实现更为完整的隐藏地址栏的效果,可参考:http://menacingcloud.com/?c=iPhoneAddressBar



原创粉丝点击