iOS开发-webView上的一些简单交互

1.实现webView上图片的等比缩放。javascript

//在webview加载完成时调用
[webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth = 300.0;" // UIWebView中显示的图片宽度
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "myimg.width = maxwidth;"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();”];

注意:必定要再webView加载完成的时候调用,若是你必定要一开始的显示调用后的界面你也能够再webView加载的时候将webView隐藏,登调用完以后在显示就好了。java

2.改变webView的字体大小,字体颜色,背景颜色等web

    //字体大小

    [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'"];

注意:这个也要在webView加载完成的时候调用。app

 

3.webView监听点击图片事件字体

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    if ([request.URL.scheme isEqualToString:@"image-preview"]) {

        NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];

        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//path就是咱们点击图片后获得的图片URL,而后你能够在这里作你点击以后要执行的代码

        return NO;

    }

    return YES;

}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    [webView stringByEvaluatingJavaScriptFromString:@"function assignImageClickAction(){var imgs=document.getElementsByTagName('img');var length=imgs.length;for(var i=0;i<length;i++){img=imgs[i];img.onclick=function(){window.location.href='image-preview:'+this.src}}}"];

    [webView stringByEvaluatingJavaScriptFromString:@"assignImageClickAction();"];

}

一般用这个能够实现点击图片全屏查看。this

相关文章
相关标签/搜索