js粘贴图片(可以显示或上传)仅支持IE11,chrome,firefox

项目中如果想支持粘贴截图上传图片,或者粘贴截图显示到某个位置,可以用这段代码,支持IE11,chrome。

注意粘贴图片不支持mac os 中的safari,safari会弹窗提示:Oops: You are trying to paste an image in Safari, however we are unable to retieve its data. 不让粘贴图片。

2016-12-01 备注:发现在windows 7中安装了firefox新版测试,这段代码无法运行,所以,请看附件代码,利用paste.js支持图片粘贴,那个可以做到在IE11,chrome,firefox中运行!

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>测试</title>
	<style type="text/css">
	#editor {width: 500px;height:300px; border: 1px solid black;cursor:text;}
	</style>
</head>
<body>
	<div id="editor" contentEditable="true">这里填写内容!</div>
	<script src="index.js"></script>
</body>
</html>
document.querySelector('#editor').onpaste = function(e) {
	//判断是否是粘贴图片				
	if (e.clipboardData && e.clipboardData.items && e.clipboardData.items[0].type.indexOf('image') > -1) {
		var that = this,
			reader = new FileReader(),
			file = e.clipboardData.items[0].getAsFile();
		reader.onload = function(e) {
			// this.result得到图片的base64 (可以用作即时显示)
			var img = '<img src="' + this.result + '" alt=""/>';
			insertAtCursor(that, img);
		}
		reader.readAsDataURL(file);
	}
};

function insertAtCursor(dom, html) {
	if (dom != document.activeElement) { // 如果dom没有获取到焦点,追加
		dom.innerHTML = dom.innerHTML + html;
		return;
	}
	var sel, range;
	if (window.getSelection) {
		// IE9 或 非IE浏览器
		sel = window.getSelection();
		if (sel.getRangeAt && sel.rangeCount) {
			range = sel.getRangeAt(0);
			range.deleteContents();
			// Range.createContextualFragment() would be useful here but is
			// non-standard and not supported in all browsers (IE9, for one)
			var el = document.createElement("div");
			el.innerHTML = html;
			var frag = document.createDocumentFragment(),
				node, lastNode;
			while ((node = el.firstChild)) {
				lastNode = frag.appendChild(node);
			}
			range.insertNode(frag);
			// Preserve the selection
			if (lastNode) {
				range = range.cloneRange();
				range.setStartAfter(lastNode);
				range.collapse(true);
				sel.removeAllRanges();
				sel.addRange(range);
			}
		}
	} else if (document.selection && document.selection.type != "Control") {
		// IE < 9
		document.selection.createRange().pasteHTML(html);
	}
}

js中用到了在DIV中的光标位置插入内容的函数:insertAtCursor。

jquery.js请自行补充。

因为上述代码在新版的firefox中无法支持,所以请看附件代码,利用paste.js支持粘贴图片。

paste.js项目地址:https://github.com/layerssss/paste.js 

猜你喜欢

转载自canlynet.iteye.com/blog/2341462
今日推荐