最近项目某个模块中要求可以实现对网页中图片的查看,并要求在多张图片的情况下可以实现滑动浏览。
所以,问题的集中点就是如何获取所有的图片地址及添加图片的点击事件。不多说,直接上码!
在网页加载完成时,通过js获取图片和添加点击的识别方式
- (void)webViewDidFinishLoad:(UIWebView*)webView {
[IDProgressHUDIDPlaceViewHideDirect:self.view];
//这里是js,主要目的实现对url的获取
staticNSString*constjsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
[webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
NSString *urlResurlt = [webViewstringByEvaluatingJavaScriptFromString:@"getImages()"];
mUrlArray = [NSMutableArrayarrayWithArray:[urlResurlt componentsSeparatedByString:@"+"]];
if(mUrlArray.count>=2) {
[mUrlArrayremoveLastObject];
}
//urlResurlt 就是获取到得所有图片的url的拼接;mUrlArray就是所有Url的数组
//添加图片可点击js
[mWebViewstringByEvaluatingJavaScriptFromString:@"function registerImageClickAction(){\
var imgs=document.getElementsByTagName('img');\
var length=imgs.length;\
for(var i=0;i
img=imgs[i];\
img.onclick=function(){\
window.location.href='image-preview:'+this.src}\
}\
}"];
[mWebViewstringByEvaluatingJavaScriptFromString:@"registerImageClickAction();"];
}
//在这个方法中捕获到图片的点击事件和被点击图片的url
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
//预览图片
if([request.URL.schemeisEqualToString:@"image-preview"]) {
NSString* path = [request.URL.absoluteStringsubstringFromIndex:[@"image-preview:"length]];
path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//path 就是被点击图片的url
returnNO;
}
return YES;
}
后记:js挺好玩,我相信以后还会去多接触它