iOS webView 載入HTML5獲取載入後的高度
阿新 • • 發佈:2019-02-19
第一種
//html5 圖片設定為螢幕寬
NSString *myStr = [NSString stringWithFormat:@"<head><style>img{max-width:%f !important;}</style></head>",screenWidth];
NSString *str = [NSString stringWithFormat:@"%@%@",myStr,html5文字];
//////////////////////////////////////////////
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//HTML5的高度
NSString *htmlHeight = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"];
//HTML5的寬度
NSString *htmlWidth = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollWidth"];
//寬高比
float i = [htmlWidth floatValue]/[htmlHeight floatValue];
//webview控制元件的最終高度
float height = screenWidth/i;
//後面的程式碼
。。。。。。
}
第二種
NSString *htmls = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {margin:18;font-size:45;color:0x666666}\n"
"</style> \n"
"</head> \n"
"<body>"
"<script type='text/javascript'>"
"window.onload = function(){\n"
"var $img = document.getElementsByTagName('img');\n"
"for(var p in $img){\n"
" $img[p].style.width = '100%%';\n"
"$img[p].style.height ='auto'\n"
"}\n"
"}"
"</script>%@"
"</body>"
"</html>",_model.content];
[_webView loadHTMLString:htmls baseURL:nil];
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *htmlHeight = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"];
NSString *htmlWidth = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollWidth"];
float i = [htmlWidth floatValue]/[htmlHeight floatValue];
float height = screenWidth/i;
//
//後面的程式碼
。。。。。。
}