ios: WebView內高亮搜索

因爲webview 加載的是網頁 只能用js 進行頁內查找  廢話不說上代碼css

// 注入 JS 查找
    NSString *resPath = [[NSBundle mainBundle] resourcePath];
    static NSString *jsQuery = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        jsQuery = [NSString stringWithContentsOfFile:[resPath stringByAppendingPathComponent:@"js_plugins.js"] encoding:NSUTF8StringEncoding error:nil];
        
    });
    NSString *js = [NSString stringWithFormat:@"var highlightPlugin = document.getElementById('js_plugins'); \
                    if (highlightPlugin == undefined) { \
                    document.body.innerHTML += '<div id=\"js_plugins\"> \
                    <style type=\"text/css\"> \
                    .utaHighlight { background-color:yellow; } \
                    .selectSpan { background-color:yellow; color:red;} \
                    </style> \
                    </div>'; \
                    %@ \
                    }", jsQuery];
    
    [self stringByEvaluatingJavaScriptFromString:js];
    
    // 清除上次的高亮並設置當前關鍵字高亮
    [self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"jQuery('body').removeHighlight().utaHighlight('%@');", str]];
    
    // 獲取關鍵字數量
    NSString *count = [self stringByEvaluatingJavaScriptFromString:@"jQuery('.utaHighlight').length"];
    
    if ([count integerValue]>0) {
        [self focusToFindIndex:0];
    }
dispatch_once 用單例的話不用每調用一次都讀取一次文件,後面就是一些調用一些js文件的方法。
可擴展上一個下一個,暫時沒有實現。
其餘具體文件方法能夠看demo
http://pan.baidu.com/s/1eQAGNPC

v 14.10.31 更新:web

增長擴展上一個和下一個,其實也很簡單lua

既然要用到上一個、下一個,確定要記錄下當前的位置,總的數量spa

1.定義兩個全局變量code

static NSInteger sCount ;//總數量
static NSInteger sNumber  = 1;//當前位置(默認從1開始)orm

2.增長上一個 下一個方法blog

- (void)nextFindIndex
{
    if (sNumber>=sCount) {
        return;
    }
    [self focusToFindIndex:sNumber];
    sNumber ++ ;
}

- (void)lastFindIndex
{
    if (sNumber<=0) {
        return;
    }
    sNumber--;
    [self focusToFindIndex:sNumber];
}

 

3.到這裏的,以前寫focusToFindIndex 方法須要修改ip

- (void)focusToFindIndex:(NSInteger)findIndex
{
    NSString *js = [NSString stringWithFormat:@"scrollToFindIdx(%d);", findIndex];
    CGFloat offset = [[self stringByEvaluatingJavaScriptFromString:js] floatValue];
    
    CGFloat contentHeight = self.scrollView.contentSize.height;
    offset = MIN(offset, contentHeight-self.scrollView.bounds.size.height);
    [self.scrollView setContentOffset:CGPointMake(0, offset) animated:YES];
}

一樣highlightAllOccurencesOfString 方法也須要修改,即給變量賦值webview

// 獲取關鍵字數量
    NSString *count = [self stringByEvaluatingJavaScriptFromString:@"jQuery('.utaHighlight').length"];
    sCount = [count intValue];
    sNumber = 1;
    if ([count intValue]>0) {
        [self focusToFindIndex:0];
    }

4.完畢rem

相關文章
相關標籤/搜索