直接貼代碼了;已經懶到極致了!javascript
需求: 解決服務器傳過來的js代碼,並正確的按想要的排版方式顯示在頁面上(即適配移動端各個屏幕)html
解決方案: 加載前提早攔截修改適配樣式 (固然也能夠前端作適配各個平臺, 不過移動端作了處理就不用理會前端是否適配的問題)前端
處理的問題有: 適配文字大小; 適配圖片大小; 適配視頻大小;java
- (void)parseHTMLWithHtml:(NSString *)htmls {web
self.content.alpha = 0;服務器
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(_imagesView.frame) , kWIDTH_SCREEN -30, kHEIGHT_SCREEN/2 )];app
[self.scroll addSubview:self.webView];ide
self.webView.scrollView.scrollEnabled = NO;lua
self.webView.delegate = self;spa
self.webView.backgroundColor = [UIColor whiteColor];
self.scroll.contentSize = CGSizeMake(kWIDTH_SCREEN -30 , CGRectGetMaxY(self.webView.frame)+64+20);
[SVProgressHUD showWithStatus:@"努力加載..."];
htmls = [htmls stringByReplacingOccurrencesOfString:@"<br/>" withString:@""];
[self.webView loadHTMLString:htmls baseURL:nil];
[self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '75%'"];
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-30 ,[UIScreen mainScreen].bounds.size.width-45];
[webView stringByEvaluatingJavaScriptFromString:js];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
NSString *js2 =@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeVideo() { "
"var number = (document.getElementsByTagName('iframe')[0].height / document.getElementsByTagName('iframe')[0].width);"
"document.getElementsByTagName('iframe')[0].width= %f;"
"document.getElementsByTagName('iframe')[0].height= document.getElementsByTagName('iframe')[0].width * number ;"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
js2 = [NSString stringWithFormat:js2,[UIScreen mainScreen].bounds.size.width-30 ];
[webView stringByEvaluatingJavaScriptFromString:js2];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeVideo();"];
CGFloat webViewHeight=[webView.scrollView contentSize].height;
CGRect newFrame = webView.frame;
newFrame.size.height = webViewHeight;
webView.frame = newFrame;
self.scroll.contentSize = CGSizeMake(kWIDTH_SCREEN - 30, CGRectGetMaxY(webView.frame) - kHEIGHT_SCREEN/3);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
}