代码改变世界

iOS调用HTML

2016-10-13 19:46  甘雨路  阅读(280)  评论(0编辑  收藏  举报
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>常用站点</title>
<!--    <link href="CSS/index.css" rel="stylesheet">-->
</head>

<body>
  <div id="header">常用站点</div>
  <div id="content">
      <ul>
          <li class="first">第一口语网——完全免费英语口语学习的专业网站</li>
          <li>hao123上网从这里开始</li>
          <li>反馈中心 - 博客园</li>
          <li>极客学院IT在线教育平台</li>
          <li>Code4App-iOS开发</li>
          <li>36氪_为创业者提供最好的产品和服务</li>
          <li>百度网盘-全部文件</li>
          <li>58同城</li>
          <li>甘雨路 - 博客园</li>
          <li>百度视频--全球最大中文视频搜索引擎</li>
          <li>我的随笔 - 博客后台 - 博客园</li>
          <li>NBA_百度搜索</li>
      </ul>
  </div>
</body>
</html>
#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>

@property (nonatomic , strong) UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建webView 
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    // 加载本地网页
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

#pragma mark -- 操作网页 --
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    // 删除
    NSString *str1 = @"var header = document.getElemenById('header'); ";
    NSString *str2 = @"header.remove();";
    [webView stringByEvaluatingJavaScriptFromString:str1];
    [webView stringByEvaluatingJavaScriptFromString:str2];
    
    // 更改网页的内容
    NSString *str3 = @"var first = document.getElementsByClassName('first')[0];" "first.innerHTML = 'Apple 官网';" ;
    [webView stringByEvaluatingJavaScriptFromString:str3];
    
    // 插入图片
    NSString *str4 = @"var img = document.createElement('img');"
                     "img.src = 'ply.png';"
                      "document.body.appendChild(img);";
    [webView stringByEvaluatingJavaScriptFromString:str4];
}

@end