前段时间需要修改webView背景色,上stackoverflow搜了很久没有找到结果,百度搜索,各种转载,各种坑爹,搜出来的都只有字体大小和字体颜色,页面背景没有看到,本人发布方法,希望可以帮助到更多人
在webView的delegate回调方法-webViewDidFinishLoad:(UIWebView*)webView;中写上一下语句即可
//字体大小
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '330%'"];
//字体颜色
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'gray'"];
//页面背景色
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#2E2E2E'"];
之前把方法写在init里怎么都不行 ,原来得写在delegate里啊 (上边的才是正确的)
- (void)initWebView
{
if (!self.myWebView){
self.myWebView = [[UIWebViewalloc] initWithFrame:self.view.bounds];
}
self.myWebView.delegate =self;
self.myWebView.opaque =NO; //不设置这个值页面背景始终是白色
self.myWebView.backgroundColor = [UIColorclearColor];
self.myWebView.scalesPageToFit =NO; //禁止用户缩放页面
self.myWebView.dataDetectorTypes =UIDataDetectorTypePhoneNumber|UIDataDetectorTypeLink;
self.myWebView.scrollView.pagingEnabled =YES;
self.myWebView.scrollView.contentInset =UIEdgeInsetsMake(0,0,0,0);
self.myWebView.autoresizingMask =UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.myWebView];
NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",16.0,[color webColorString]];
[self.myWebViewstringByEvaluatingJavaScriptFromString:jsString];
}