1 viewport属性放在HTML的<meta>中
<span style="font-size: x-small;"> <head> <title>Exmaple</title> <meta name=”viewport” content=”width=device-width,user-scalable=no”/> </head></span>meta中viewport的属性如下
<span style="font-size: x-small;"> <meta name="viewport" content=" height = [pixel_value | device-height] , width = [pixel_value | device-width ] , initial-scale = float_value , minimum-scale = float_value , maximum-scale = float_value , user-scalable = [yes | no] , target-densitydpi = [dpi_value | device-dpi | high-dpi | medium-dpi | low-dpi] " /></span>2 CSS控制设备密度为每种密度创建独立的样式表(注意其中的webkit-device-pixel-ratio 3个数值对应3种分辨率)
<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.5)" href="hdpi.css" /> <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.0)" href="mdpi.css" /> <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 0.75)" href="ldpi.css" /> #header { <span style="white-space: pre;"> </span> background:url(medium-density-image.png); } @media screen and (-webkit-device-pixel-ratio: 1.5) { // CSS for high-density screens #header { background:url(high-density-image.png); } } @media screen and (-webkit-device-pixel-ratio: 0.75) { // CSS for low-density screens #header { background:url(low-density-image.png); } }
<meta name="viewport" content="target-densitydpi=device-dpi, width=device-width" />3 JS控制
if (window.devicePixelRatio == 1.5) { alert("This is a high-density screen"); } else if (window.devicePixelRation == 0.75) { alert("This is a low-density screen"); }Android中构建HTML5应用
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.loadUrl("http://www.baidu.com");
注意在manifest文件中加入访问互联网的权限: <uses-permission android:name="android.permission.INTERNET" />在Android中点击一个链接,默认是调用应用程序来启动,因此WebView需要代为处理这个动作 通过WebViewClient
webView.setWebViewClient(new WebViewClient(){ public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } });
private class MyWebViewClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals("www.example.com")) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }之后:
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setWebViewClient(new MyWebViewClient());出于用户习惯上的考虑 需要将WebView表现得更像一个浏览器,也就是需要可以回退历史记录因此需要覆盖系统的回退键 goBack,goForward可向前向后浏览历史页面
public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() { myWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); }