UIWebView加载html,使网页中的图片可点击

第一步:UIWebView 加载要显示的html,可来自网络,也可来自本地。

[_webViewloadHTMLString:htmlStringbaseURL:nil];

第二步:将javascript嵌入页面中

(1)//给webView引用自定义的javascript,我在这里是写在了一个js文件里

NSString*filePath = [[NSBundlemainBundle]pathForResource:@"ClickImg"ofType:@"js"];

NSString*js = [NSStringstringWithContentsOfFile:filePathencoding:NSUTF8StringEncodingerror:nil];

[webViewstringByEvaluatingJavaScriptFromString:js];

(2)网页加载完毕后,为img元素添加onClick事件,即onClick触发上述js文件中的setImage方法

- (void)webViewDidFinishLoad:(UIWebView*)webView{

[_webViewstringByEvaluatingJavaScriptFromString:@"setImage()"];

}

这里的就是调用js文件的setImage方法。

第三步:处理点击事件

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType{

NSString*requestString = [[requestURL]absoluteString];

NSArray*components = [requestStringcomponentsSeparatedByString:@":"];

if([componentscount] >=1) {

//判断是不是图片点击

if([(NSString*)[componentsobjectAtIndex:0]isEqualToString:@"imageclick"]) {

UIAlertView*alert = [[UIAlertViewalloc]

initWithTitle:@"click"

message:components[1]

delegate:selfcancelButtonTitle:nil

otherButtonTitles:@"OK",nil];

[alertshow];

returnNO;

}

returnYES;

}

returnYES;

}

你可能感兴趣的:(UIWebView加载html,使网页中的图片可点击)