我有一个基本的网页,当它在Android平板电脑(Nexus 7)上的Chrome中显示时,可以正确响应屏幕尺寸和方向变化(使用CSS媒体查询)。当我在WebView中显示同一页面时,基于屏幕宽度的媒体查询不起作用。这是我设置WebView的方法:
WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.loadUrl("http://10.0.1.8:8080/cbc/test");
WebView根据以下媒体查询的行为正确检测方向变化:
@media only screen and (orientation: portrait) {
.landscape { display: none; }
}
@media only screen and (orientation: landscape) {
.portrait { display: none; }
}
使用屏幕尺寸的媒体查询无法正常工作,因为根据以下JavaScript,屏幕宽度和高度会通过方向更改而保持不变:
$("#dimensions").empty();
$("#dimensions").append($("<div>Width: " + screen.width + "</div>"));
$("#dimensions").append($("<div>Height: " + screen.height + "</div>"));
$("#dimensions").append($("<div>Depth: " + screen.pixelDepth + "</div>"));
我使用“orientationchange”事件触发了先前的代码。在Android上的Chrome中运行时,宽度和高度值会正确显示,并考虑了设备方向。在WebView中运行时,宽度和高度保持不变,而与方向无关。
我需要将某些配置应用于WebView以获得预期的行为吗?
最佳答案
尝试在您的JavaScript中查看window.innerWidth
和window.innerHeight
。