//設置背景透明
[_webview setOpaque:NO];
//初始化
_webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, _height * 0.15, _width, _height * 0.8)];
_webView.dataDetectorTypes = UIDataDetectorTypeAll;
_webView.backgroundColor = [UIColor clearColor];
[_webView setOpaque:NO];
//加載本地的HTML文件
NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil];
// NSURL *htmlURL = [NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:htmlURL];
// 如果不想要webView 的回彈效果
self.webView.scrollView.bounces = NO;
// UIWebView 滾動的比較慢靶剑,這里設置為正常速度
self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
[self.webView loadRequest:request];
[self.view addSubview:self.webView];
注入JS
//webView加載完成
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//js代碼
NSString *jsString = @"(function(){"
"var objs = document.getElementsByTagName('img');"
"for(var i=0,j=0;i<objs.length;i++)"
"{"
" var levelcode = objs[i].getAttribute('levelcode');"
" if(levelcode=='-1'){"
"continue;"
"}"
"objs[i].setAttribute('index',j);"
"j++;"
"objs[i].onclick=function()"
"{"
"var index = this.getAttribute('index');"
"openImage(index);"
"}"
"}"
"})()";
__weak typeof(self) weakSelf = self;
[webView stringByEvaluatingJavaScriptFromString:jsString];
//其中 openImage 是JS的函數(shù)名,得到的 arg數(shù)組 里面為JS的 passValue 函數(shù)的參數(shù)闻察,即 JS要傳給OC的參數(shù)痹雅。
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"openImage"] = ^{
NSString *string;
NSArray *arg = [JSContext currentArguments];
for (id obj in arg) {
string = [NSString stringWithFormat:@"%@",obj];
}
dispatch_async(dispatch_get_main_queue(), ^{
NewDetailScrollViewController *vc = [[NewDetailScrollViewController alloc]init];
[vc loadUIWithdataDict:weakSelf.dict indexImage:[string integerValue] isSearch:weakSelf.isSearch];
[weakSelf.navigationController pushViewController:vc animated:YES];
});
};
}