Coder Social home page Coder Social logo

pphtmlimagepreviewdemo's Introduction

PPHTMLImagePreviewDemo

概述

该DEMO主要用于演示iOS APP中点击HTML的图片来实现本地预览,如下是演示图 image

原理阐述

1. 背景知识

在了解该原理之前,需要知道如下内容

  • html中的点击动作一般都是通过javascript来实现的,如下面代码:
var img = document.getElementById('test');
img.onclick = function() {
	alert("test");
}

PS: 以上代码实现的是点击< img id="test">来弹出含test的提示框. 当然可以通过getElementsByTagName,getElementsByClassName获取标签元素

  • javascript与objc交互

在iOS APP开发过程中,是通过UIWebView来加载html页面,因此javascript要与objc交互,桥梁应该就在UIWebview提供的API中,通过查找,发现如下一些接口:

//objc 传参给javascript
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

//javascript 传参给objc, 参数是存在于request中
 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

2. 实现细节

  • 在UIWebview加载完html后,调用stringByEvaluatingJavaScriptFromString来执行如下javascript代码,可以使用javascript压缩工具压缩下
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
		}
	}
}
assignImageClickAction();
  • 在webView:shouldStartLoadWithRequest:navigationType处理image-preview

许可

该代码遵循MIT许可.

联系方式

email: [email protected]

pphtmlimagepreviewdemo's People

Contributors

smallmuou avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.