這篇文章主要介紹了JS互動點擊WKWebView中的圖片實現預覽效果,需要的朋友可以參考下
Swift 4.0
#WKWebView
1.注入js程式碼(重點)
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { let jsGetImages = "function getImages(){" + "var objs = document.getElementsByTagName(\"img\");" + "var imgScr = '';" + "for(var i=0;i<objs.length;i++){" + "imgScr = imgScr + objs[i].src + '+';" + "};" + "return imgScr;" + "};" webView.evaluateJavaScript(jsGetImages, completionHandler: nil) webView.evaluateJavaScript("getImages()") { (data, err) in let imageUrl:String = data as! String var urlArry = imageUrl.components(separatedBy: "+") urlArry.removeLast() self.imgUrlArray.addObjects(from: urlArry) for url in self.imgUrlArray{ let photo = SKPhoto.photoWithImageURL(url as! String) photo.shouldCachePhotoURLImage = false // you can use image cache by true(NSCache) self.images.append(photo) } } var jsClickImage:String jsClickImage = "function registerImageClickAction(){" + "var imgs=document.getElementsByTagName('img');" + "var length=imgs.length;" + "for(var i=0;i<length;i++){" + "img=imgs[i];" + "img.onclick=function(){" + "window.location.href='image-preview:'+this.src}" + "}" + "}" webView.evaluateJavaScript(jsClickImage, completionHandler: nil) webView.evaluateJavaScript("registerImageClickAction()", completionHandler: nil) }
2.使用SKPhotoBrowser框架實作圖片預覽功能
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let requestString = navigationAction.request.url?.absoluteString print(requestString!) if (requestString?.hasPrefix("image-preview"))!{ let imgUrl = NSString.init(string: requestString!).substring(from: "image-preview:".count ) let index = imgUrlArray.index(of: imgUrl) let browser = SKPhotoBrowser(photos: images) browser.initializePageIndex(index) present(browser, animated: true, completion: {}) } decisionHandler(.allow) //一定要加上这句话 }
上面是我整理給大家的,希望今後會對大家有幫助。
相關文章:
################################在微信小程式中如何使用slider元件############在vue中如何實作記住密碼到cookie上############AngularJS重要版本更新## ##########在微信小程式中有關button元件的使用說明######以上是在JS中如何實現預覽效果的詳細內容。更多資訊請關注PHP中文網其他相關文章!