美文网首页
webview加载html标签字符串时,手动嵌入内容格式控制来适

webview加载html标签字符串时,手动嵌入内容格式控制来适

作者: ChendiYeahNet | 来源:发表于2018-11-17 15:41 被阅读0次
    • (void)setupHtmlContent:(NSString *)contentHtml loadedComplete:(void(^)(BOOL result,CGFloat webViewConetntHeight))complete {

      self.loadedComplete = complete;

      if (contentHtml.length > 0) {
      NSString contentStyle = [NSString stringWithFormat:@"<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"><style>img{width:%fpx !important;}</style></head>",ScreenWidth - 182.0];

        NSString *html = [NSString stringWithFormat:@"<html>%@<body style=\"word-wrap:break-word; margin: 0 auto; padding: 0 15px; font-family:Arial\">%@</body></html>",contentStyle,contentHtml];
      
        [self.webView loadHTMLString:html baseURL:[NSURL URLWithString:kDomainUrl]];
      

      } else {
      complete ? complete(NO, 0) : nil;
      }
      }

    pragma mark - add js method to webView

    • (void)addImgClickedJsEventToWebView {
      // 1、加载完成之后开始注入js事件
      [self.webView evaluateJavaScript:@"
      function imageClickAction(){
      var imgs=document.getElementsByTagName('img');
      var length=imgs.length;
      for(var i=0;i<length;i++){
      img=imgs[i];
      img.onclick=function(){
      window.location ='mobile-store-image-preview:'+this.src;
      }
      }
      }
      " completionHandler:^(id _Nullable result,NSError * _Nullable error) {}];
      // 2、触发方法 给所有的图片添加onClick方法
      [self.webView evaluateJavaScript:@"imageClickAction();" completionHandler:^(id _Nullable result,NSError * _Nullable error) {}];

      // 3、要拿到所有img标签对应的图片的src
      [self.webView evaluateJavaScript:@"document.getElementsByTagName('img').length" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
      // 3.1、拿到img标签的个数
      NSUInteger length = [result integerValue];
      // 3.2、遍历标签,拿到标签中src的内容
      for (int i =0 ; i < length; i++) {
      NSString *jsStr = [NSString stringWithFormat:@"document.getElementsByTagName('img')[%d].src",i];
      [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result,NSError * _Nullable error) {
      EOADetailLog(@"%@",result);
      // 3.3、将标签中src内容存入数组
      if ([self.imgsArray containsObject:result] == NO) {
      [self.imgsArray addObject:result];
      }
      }];
      }
      }];
      }

    • (void)jumpPreviewImagePageWithImageUrl:(NSString *)imgUrl {
      NSInteger index = [self.imgsArray indexOfObject:imgUrl];
      CDPreviewPictureVC *previewVC = [[CDPreviewPictureVC alloc] initWithBrowseUrlPictures:self.imgsArray startAtIndex:index onClicked:nil];
      [self.viewController presentViewController:previewVC animated:NO completion:nil];
      }

    相关文章

      网友评论

          本文标题:webview加载html标签字符串时,手动嵌入内容格式控制来适

          本文链接:https://www.haomeiwen.com/subject/sffifqtx.html