ios 使用webview 查找_ios: WebView内高亮搜索

由于webview 加载的是网页 只能用js 进行页内查找  废话不说上代码

//注入 JS 查找

NSString *resPath =[[NSBundle mainBundle] resourcePath];static NSString *jsQuery =nil;staticdispatch_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 += '

\

.utaHighlight { background-color:yellow; } \

.selectSpan { background-color:yellow; color:red;} \\

'; \

%@ \

}", 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 更新:

增加扩展上一个和下一个,其实也很简单

既然要用到上一个、下一个,肯定要记录下当前的位置,总的数量

1.定义两个全局变量

static NSInteger sCount ;//总数量

static NSInteger sNumber  = 1;//当前位置(默认从1开始)

2.增加上一个 下一个方法

- (void)nextFindIndex

{if (sNumber>=sCount) {return;

}

[self focusToFindIndex:sNumber];

sNumber++;

}- (void)lastFindIndex

{if (sNumber<=0) {return;

}

sNumber--;

[self focusToFindIndex:sNumber];

}

3.到这里的,之前写focusToFindIndex 方法需要修改

- (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 方法也需要修改,即给变量赋值

//获取关键字数量

NSString *count = [self stringByEvaluatingJavaScriptFromString:@"jQuery('.utaHighlight').length"];

sCount= [count intValue];

sNumber= 1;

if ([count intValue]>0) {

[self focusToFindIndex:0];

}

4.完毕

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值