-
webView--圖片自適應(yīng)屏幕
- HTML修改
- 代碼修改
-(void)viewDidLoad {
[super viewDidLoad];
// 設(shè)置webView
UIWebView *webView=[[UIWebView alloc]initWithFrame:self.view.bounds];
// 1嫉拐、本地html資源測(cè)試
// NSString *path=[[NSBundle mainBundle]pathForResource:@"test" ofType:@"html"];
// [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];
// 2、URL網(wǎng)址資源測(cè)試
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://gb.wallpapersking.com/top/class108/15041/14eec4d8b4bf1fe0.htm"]]];
[self.view addSubview:webView];
webView.delegate=self;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *js=@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth = %f;"
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = %f;"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
js=[NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width-15];
[webView stringByEvaluatingJavaScriptFromString:js];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}
在請(qǐng)求內(nèi)部設(shè)置
// 網(wǎng)絡(luò)請(qǐng)求加載的數(shù)據(jù),進(jìn)行字典轉(zhuǎn)模型
NSDictionary *dict = [result objectForKey:@"data"];
HQNewsDetailModel *model = [HQNewsDetailModel mj_objectWithKeyValues:dict];
/**
* model.details就是后臺(tái)返回的HTMLString
* " $img[p].style.width = '100%%';\n"--->就是設(shè)置圖片的寬度的
* 100%代表正好為屏幕的寬度
*/
NSString *htmlString = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-size:15px;}\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.details];
// webView直接加載HTMLString
[self.webView loadHTMLString:htmlString baseURL:nil];