iOS項目之獲取WebView的高度


  獲取高度值的方法:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 獲取webView的高度
    CGFloat webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    CGFloat webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    CGFloat webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.clientHeight"] floatValue];
}

 

  遇到的問題:在這里采用的是加載HTML代碼,由於前端H5中格式問題,網頁中圖片過大,顯示不完整,於是自己做了以下處理,使圖片適配屏幕大小

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 1、只對本地html資源的圖片有效果
    NSString *js = @"function imgAutoFit() { \
                    var imgs = document.getElementsByTagName('img'); \
                    for (var i = 0; i < imgs.length; ++i) {\
                        var img = imgs[i];   \
                        img.style.maxWidth = %f;   \
                        } \
                    }";
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
    [self.myWebView stringByEvaluatingJavaScriptFromString:js];
    [self.myWebView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    
    
    // 獲取webView的高度
    CGFloat webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    NSLog(@"%.f", webViewHeight);
}

  但是這樣做的話,獲取的網頁高度還是以前一樣的內容高度,但圖片改變了大小,導致網頁下方留出了多余的空白。

  於是再次進行了修改,將獲取到的HTML代碼拼接一個格式后,再來請求HTML網頁,

    /*- 在加載網頁時添加代碼 -*/ 
    // 手動改變圖片適配問題,拼接html代碼后,再加載html代碼
    NSString *myStr = [NSString stringWithFormat:@"<head><style>img{max-    width:%f !important;}</style></head>", [UIScreen mainScreen].bounds.size.width - 20];
    NSString *str = [NSString stringWithFormat:@"%@%@",myStr, html5代碼];
    [self.myWebView loadHTMLString:str baseURL:nil];
     /*- 在加載網頁時添加代碼 -*/ 


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 獲取webView的高度
    CGFloat webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
  NSLog(@"%.f",webViewHeight);
}

  這樣就完美適配屏幕大小了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM