Android WebView和CSS媒体查询

Tom*_*rry 6 css android webview

我有一个基本的网页,当在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");
Run Code Online (Sandbox Code Playgroud)

WebView根据以下媒体查询的行为正确检测方向更改:

@media only screen and (orientation: portrait) {
    .landscape { display: none; }
}

@media only screen and (orientation: landscape) {
    .portrait { display: none; }
}
Run Code Online (Sandbox Code Playgroud)

使用屏幕尺寸的媒体查询无法正常工作,因为根据以下JavaScript,屏幕宽度和高度通过方向更改保持不变:

    $("#dimensions").empty();
    $("#dimensions").append($("<div>Width: " + screen.width + "</div>"));
    $("#dimensions").append($("<div>Height: " + screen.height + "</div>"));
    $("#dimensions").append($("<div>Depth: " + screen.pixelDepth + "</div>"));
Run Code Online (Sandbox Code Playgroud)

我使用"orientationchange"事件触发前面的代码.在Android上的Chrome中运行时,会正确显示宽度和高度值,并将设备方向考虑在内.在WebView内部运行时,无论方向如何,宽度和高度都保持不变.

是否有一些配置需要应用于WebView以获得预期的行为?

Kev*_*nch -1

当谈到现代屏幕时,您需要指定像素比。CSS 术语中的像素是一种测量,而不是实际的像素。由于高分辨率屏幕和视网膜显示屏,像素大小有所不同。制造商尝试根据像素作为尺寸进行显示,但它不能正确地与媒体查询一起使用。您需要像这样进行媒体查询:

@media
  only screen and (-webkit-min-device-pixel-ratio: 2),
  only screen and (   min--moz-device-pixel-ratio: 2),
  only screen and (     -o-min-device-pixel-ratio: 2/1) { 
      //CSS here
}
Run Code Online (Sandbox Code Playgroud)