上篇文章讲过,oc和js交互,oc调用js关键的方法是
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
当我们执行stringByEvaluatingJavaScriptFromString这个方法的时候,系统会识别js,帮我们运行js代码。上代码:
//创建webView
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 400)];
webView.delegate = self;
webView.scrollView.delegate = self;
[self.view addSubview:webView];
self.webView = webView;
//html
NSString *htmlStr = @"<body style=\"border: 2px solid\"><br><p style=\"border: 2px solid mediumaquamarine\">这是第一段文字</p><p style=\"border:5px solid lightpink\">这是第二段文字</p><p style=\"border:8px solid lime\">这是第三段文字</p></body>";
//加载HTML
[webView loadHTMLString:htmlStr baseURL:nil];
按钮的点击事件
1)oc调用js 改变p标签的背景颜色
- (IBAction)clickFirst:(id)sender{
[self.webView stringByEvaluatingJavaScriptFromString:@"var p = document.getElementsByTagName('p'); p[0].style.backgroundColor='red';"];
}
2)oc调用js 文本居中显示
- (IBAction)clickSecond:(id)sender{
[self.webView stringByEvaluatingJavaScriptFromString:@"var p = document.getElementsByTagName('p'); p[1].style.textAlign='center';p[1].style.color='red'"];
}
3)oc调用js 改变文本内容
- (IBAction)clickThird:(id)sender{
[self.webView stringByEvaluatingJavaScriptFromString:@"var p = document.getElementsByTagName('p'); p[2].innerText='你没与如期而来,这就是离别的意义';"];
}
4)还原
- (IBAction)clickfourth:(id)sender{
[self.webView stringByEvaluatingJavaScriptFromString:@"var p = document.getElementsByTagName('p');p[2].innerText='这是第三段文字'; for (var i=0;i<p.length;i++){p[i].style.textAlign='';p[i].style.backgroundColor='';p[i].style.color='black';};"];
}
示例gif
github demo地址:https://github.com/shimminZ/oc-called-js
欢迎star 谢谢哇~~