1、加载本地html代码
这段代码加载了项目资源路径下www目录里面的index.html文件
NSString *path = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html" inDirectory:@"www"]; NSURL *url = [NSURL fileURLWithPath:path]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; [_webView loadRequest:req];
2、加载网络html代码
NSString *fullURL = @"http://ruby-china.org/"; NSURL *url = [NSURL URLWithString:fullURL]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [_webView loadRequest:requestObj];
3、原生代码运行页面里面的js代码
[self.webView stringByEvaluatingJavaScriptFromString:@"alert("Calling from native code");"];
4、响应式布局
对于针对html5平台的html页面,一般都会在head里面添加这样的代码,它能自适应不同尺寸和分辨率密度的屏幕
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
5、针对触摸屏优化
这是一段非常神奇的js代码,能够让你的页面中所有<a>标签的跳转,在触摸屏上面的响应速度有一个质的飞跃!对于用户体验的提升,能使得html页面最大化的近似原生应用。
{ var touching_flag = false; $(document).on('touchstart', "a:not(.notouch):not([href='#'])", function () { if (!touching_flag) { touching_flag = true; } window.setTimeout(function () { touching_flag = false; }, 0); return false; }); $(document).on('touchend', "a:not(.notouch):not([href='#'])", function () { window.location.href = $(this).attr('href'); touching_flag = false; }); }
6、通过js调用原生代码
首先,在初始化webview的时候,在你的ViewController里面令
- (void)viewDidLoad { [super viewDidLoad]; self.webView.delegate = self; }
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *jsMethodString = [[request URL] absoluteString]; NSLog(@"jsMethodString ===> %@", jsMethodString); }
接下来,你就能在html里面通过调用js来触发上面那个方法了:
function myAlert(msg) { alert(msg); window.location = 'ios:' + msg; }
jsMethodString ===> ios:This is a message from js!
7、对于提升用户体验非常有用的十个代码片段
http://www.jquery4u.com/plugins/10-jquery-ipad-code-snippets-plugins/