Hybrid app开发获取webview屏幕宽度

如果你以为用screen.width就可以获取到屏幕的宽度,没错,
但如果你想获取的是全屏webview浏览器的页面宽度,那么不出意外,错了。
比如手机屏幕1920x1080像素,那么你screen.width获取到的结果将是1080
也就是说真实的screen.width获取的是手机屏幕的宽度,与webview浏览器的宽度是不同的。
不同的操作系统webview浏览器使用的分辨率不同,主流的宽度为 320 480 720 1080 等各种尺寸


由于我们的页面基本上都会使用meta标签来定义移动端页面展示:
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
这里的width=device-width代表是可视区域的宽度为屏幕宽度,并不是说值相等,而是说浏览器中css的1px代表了n个屏幕像素点。
你可以通过window.innerWidth来获取,但是部分操作系统上可能有误(Android 2, Oprea mini 和 UC 8)
(参考:http://www.cnblogs.com/2050/p/3877280.html)


你也可以通过document.body.clientWidth或document.documentElement.clientWidth来获取,但值获取正确与否,与你是否使用了html相应的API有关,即
1、若网页中含有有了标准声明(即页面加上<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">这行代码,标准声明的存在会对document.body和document.documentElement的属性值有影响)时,则应该使用document.documentElement
2、若网页中只有<html>而没有上面的一行代码,则JS脚本应该使用document.body


(参考:http://www.tc5u.com/javascript/2085815.htm)


        console.log("screen.width=" + screen.width + ",height=" + screen.height);
        console.log("window.screen.width=" + window.screen.width);
        console.log("document.body.clientWidth.screen.width=" + document.body.clientWidth);
        console.log("document.documentElement.clientWidth.screen.width=" + document.documentElement.clientWidth);
        console.log("window.innerWidth.screen.width=" + window.innerWidth);
-------------结果------------------------------------------------------------------------------
screen.width=1080,height=1776
window.screen.width=1080
document.body.clientWidth.screen.width=360
document.documentElement.clientWidth.screen.width=360
window.innerWidth.screen.width=360
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值