兼容Android 和 ios JavaScript copy paste

<!DOCTYPE html>
<html>
	<head>
		<title>关于我们Frame</title>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<meta name="copyright" content="www.acc5.com" />
		<style>

		</style>
		<script src="http://www.acc5.com/xueli/js/jquery-1.11.3.js"></script>
		<script src="http://app-static.acc5.com/app/copy2clipboard.js"></script>

	</head>
	<body>
		hello ,welcome!!!

		<input id="test" type=‘text‘ value=‘test text144‘ /><br>
		<button onclick="select_all_and_copy(document.getElementById(‘test‘))">Copy to Clipboard</button>
	</body>
			<script>

			$().ready(function(){

					$(‘#test‘).val(‘test‘+Math.random());
					try{
					  document.execCommand(‘copy‘);
					}catch(e){}

			})

			/*
			function iosCopyToClipboard(el) {
				var oldContentEditable = el.contentEditable,
					oldReadOnly = el.readOnly,
					range = document.createRange();

				el.contenteditable = true;
				el.readonly = false;
				range.selectNodeContents(el);

				var s = window.getSelection();
				s.removeAllRanges();
				s.addRange(range);

				el.setSelectionRange(0, 999999); // A big number, to cover anything that could be inside the element.

				el.contentEditable = oldContentEditable;
				el.readOnly = oldReadOnly;

				document.execCommand(‘copy‘);
			}
			iosCopyToClipboard(document.getElementById(‘test‘))
			*/
		</script>
</html>
function tooltip(el, message)
{
	var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
	var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
	var x = parseInt(el.getBoundingClientRect().left) + scrollLeft + 10;
	var y = parseInt(el.getBoundingClientRect().top) + scrollTop + 10;
	if (!document.getElementById("copy_tooltip"))
	{
		var tooltip = document.createElement(‘div‘);
		tooltip.id = "copy_tooltip";
		tooltip.style.position = "absolute";
		tooltip.style.border = "1px solid black";
		tooltip.style.background = "#dbdb00";
		tooltip.style.opacity = 1;
		tooltip.style.transition = "opacity 0.3s";
		tooltip.style.zIndex = "1999999999"; // Version 1.2b
		document.body.appendChild(tooltip);
	}
	else
	{
		var tooltip = document.getElementById("copy_tooltip")
	}
	tooltip.style.opacity = 1;
	tooltip.style.display = "block"; // Version 1.2b
	tooltip.style.left = x + "px";
	tooltip.style.top = y + "px";
	tooltip.innerHTML = message;
	setTimeout(function() { tooltip.style.display = "none"; tooltip.style.opacity = 0; }, 2000);
}

function paste(el)
{
   	if (window.clipboardData) {
	   	// IE
    	el.value = window.clipboardData.getData(‘Text‘);
    	el.innerHTML = window.clipboardData.getData(‘Text‘);
    }
    else if (window.getSelection && document.createRange) {
        // non-IE
        if (el.tagName.match(/textarea|input/i) && el.value.length < 1)
        	el.value = " "; // iOS needs element not to be empty to select it and pop up ‘paste‘ button
        else if (el.innerHTML.length < 1)
        	el.innerHTML = " "; // iOS needs element not to be empty to select it and pop up ‘paste‘ button
        var editable = el.contentEditable; // Record contentEditable status of element
        var readOnly = el.readOnly; // Record readOnly status of element
       	el.contentEditable = true; // iOS will only select text on non-form elements if contentEditable = true;
       	el.readOnly = false; // iOS will not select in a read only form element
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        if (el.nodeName == "TEXTAREA" || el.nodeName == "INPUT")
        	el.select(); // Firefox will only select a form element with select()
        if (el.setSelectionRange && navigator.userAgent.match(/ipad|ipod|iphone/i))
        	el.setSelectionRange(0, 999999); // iOS only selects "form" elements with SelectionRange
        if (document.queryCommandSupported("paste"))
       	{
			var successful = document.execCommand(‘Paste‘);
		    if (successful) tooltip(el, "Pasted.");
		    else
			{
				if (navigator.userAgent.match(/android/i) && navigator.userAgent.match(/chrome/i))
				{
					tooltip(el, "Click blue tab then click Paste");

						if (el.tagName.match(/textarea|input/i))
						{
			        		el.value = " "; el.focus();
			        		el.setSelectionRange(0, 0);
			        	}
			        	else
			        		el.innerHTML = "";

				}
				else
					tooltip(el, "Press CTRL-V to paste");
			}
		}
		else
		{
		    if (!navigator.userAgent.match(/ipad|ipod|iphone|android|silk/i))
				tooltip(el, "Press CTRL-V to paste");
		}
		el.contentEditable = editable; // Restore previous contentEditable status
        el.readOnly = readOnly; // Restore previous readOnly status
    }
}

function select_all_and_copy(el)
{
    // Copy textarea, pre, div, etc.
	if (document.body.createTextRange) {
        // IE
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
        textRange.execCommand("Copy");
		tooltip(el, "Copied!");
    }
	else if (window.getSelection && document.createRange) {
        // non-IE
        var editable = el.contentEditable; // Record contentEditable status of element
        var readOnly = el.readOnly; // Record readOnly status of element
       	el.contentEditable = true; // iOS will only select text on non-form elements if contentEditable = true;
       	el.readOnly = false; // iOS will not select in a read only form element
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range); // Does not work for Firefox if a textarea or input
        if (el.nodeName == "TEXTAREA" || el.nodeName == "INPUT")
        	el.select(); // Firefox will only select a form element with select()
        if (el.setSelectionRange && navigator.userAgent.match(/ipad|ipod|iphone/i))
        	el.setSelectionRange(0, 999999); // iOS only selects "form" elements with SelectionRange
        el.contentEditable = editable; // Restore previous contentEditable status
        el.readOnly = readOnly; // Restore previous readOnly status
	    if (document.queryCommandSupported("copy"))
	    {
			var successful = document.execCommand(‘copy‘);
		    if (successful) tooltip(el, "Copied to clipboard.");
		    else tooltip(el, "Press CTRL+C to copy");
		}
		else
		{
			if (!navigator.userAgent.match(/ipad|ipod|iphone|android|silk/i))
				tooltip(el, "Press CTRL+C to copy");
		}
    }
} // end function select_all_and_copy(el) 

function make_copy_button(el)
{
	//var copy_btn = document.createElement(‘button‘);
	//copy_btn.type = "button";
	var copy_btn = document.createElement(‘span‘);
	copy_btn.style.border = "1px solid black";
	copy_btn.style.padding = "5px";
	copy_btn.style.cursor = "pointer";
	copy_btn.style.display = "inline-block";
	copy_btn.style.background = "lightgrey";
	copy_btn.setAttribute("role", "button");
	copy_btn.setAttribute("tabindex", 0);

	el.parentNode.insertBefore(copy_btn, el.nextSibling);
	copy_btn.onclick = function() { select_all_and_copy(el); };

	//if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42)
	// Above caused: TypeError: ‘null‘ is not an object (evaluating ‘navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]‘) in Safari
	if (document.queryCommandSupported("copy"))
	{
		// Desktop: Copy works with IE 4+, Chrome 42+, Firefox 41+, Opera 29+
		// Mobile: Copy works with Chrome for Android 42+, Firefox Mobile 41+
		//copy_btn.value = "Copy to Clipboard";
		copy_btn.innerHTML = "Copy to Clipboard";
	}
	else
	{
		// Select only for Safari and older Chrome, Firefox and Opera
		/* Mobile:
				Android Browser: Selects all and pops up "Copy" button
				iOS Safari: Selects all and pops up "Copy" button
				iOS Chrome: Form elements: Selects all and pops up "Copy" button
		*/
		//copy_btn.value = "Select All";
		copy_btn.innerHTML = "Select All";

	}
}
/* Note: document.queryCommandSupported("copy") should return "true" on browsers that support copy
	but there was a bug in Chrome versions 42 to 47 that makes it return "false".  So in those
	versions of Chrome feature detection does not work!
	See https://code.google.com/p/chromium/issues/detail?id=476508
*/

  

from:http://www.seabreezecomputers.com/tips/copy2clipboard.htm

from:https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios

原文地址:https://www.cnblogs.com/xuan52rock/p/9013036.html

时间: 2024-10-27 16:29:43

兼容Android 和 ios JavaScript copy paste的相关文章

【转】Unity上同时兼容Android和IOS的JSON库

转自卡神博客Unity上同时兼容Android和IOS的JSON库 虽然说JSON解析很常见,而且也经常看见大家讨论怎么解析.但是还是很多人经常出现各种问题.这篇文章就一次性帮你解决JSON解析的问题. 本篇文章使用JSON解析在真实项目中使用,同时兼容PC.android和IOS.没啥好说,一个C#写的解析JSON的工具类,在unity中能正常解析. 不太好用的JSON解析库:LitJson在IOS上不稳定,有时正常,有时不正常..MiniJson据说支持不完整,没测试. 本文给出的JSON解

刮刮乐JS 兼容android和ios

修正了在Android下刮不动的bug (function(bodyStyle) { bodyStyle.mozUserSelect = 'none'; bodyStyle.webkitUserSelect = 'none'; var $canvas = $(".canvas"); var moveTime,canvasTop=$canvas.offset().top; $canvas.attr("data-flag","true"); var

移动端HTML5页面端去掉input输入框的白色背景和边框(兼容Android和ios)

前两天在开发在微信访问的HTML5页面,里面有个订单查询要选择时间,刚开始使用的<input type="date">输入框,没加任何的样式,效果是白色的背景再加上边框很丑,完 全与整个背景不协调. 刚开始设置了输入框背景色透明(background-color:transparent;),在ios上面背景色和边框都没有了,但是在andriod上边框和背景色还是存在.后来加上样式FILTER: alpha(opacity=0),在andriod中就去掉了边框和背景. 去掉背

多平台实现密码强度(Javascript 、android、ios)

密码强度是目前很常用的一种功能,密码强度的实现,在web端都很好实现,可以很轻松的使用Javascript方法实现,目前因为项目需要,要在手机app上也实现密码强度,并且同时要在Android和ios上都实现相同功能,密码复杂度,无外乎大写字母.小写字母.数字和特殊符号,且需要加上重复字符出现的次数等,一般常用的方法都是使用正则表达式. 查阅了很多资料,网上在app端实现密码强度的例子基本没有(手机QQ是调用的web页面,支付根本没有密码复杂度),且又要web端和app端的三种语言通用,没办法只

GitHub Android 最火开源项目Top20 GitHub 上的开源项目不胜枚举,越来越多的开源项目正在迁移到GitHub平台上。基于不要重复造轮子的原则,了解当下比较流行的Android与iOS开源项目很是必要。利用这些项目,有时能够让你达到事半功倍的效果。

1. ActionBarSherlock(推荐) ActionBarSherlock应该算得上是GitHub上最火的Android开源项目了,它是一个独立的库,通过一个API和主题,开发者就可以很方便地使用所有版本的Android动作栏的设计模式. 对于Android 4.0及更高版本,ActionBarSherlock可以自动使用本地ActionBar实现,而对于之前没有ActionBar功能的版本,基于Ice Cream Sandwich的自定义动作栏实现将自动围绕布局.能够让开发者轻松开发

【移动端兼容问题研究】javascript事件机制详解(涉及移动兼容)--转

前言 javascript事件基础 事件捕获/冒泡 事件对象 事件模拟 移动端响应速度 PC与移动端鼠标事件差异 touch与click响应速度问题 结论 zepto事件机制 注册/注销事件 zepto模拟tap事件 tap事件的问题一览 点透问题 fastclick思想提升点击响应 实现原理 鬼点击 ios与android鼠标事件差异 事件捕获解决鬼点击 结语 前言 这篇博客有点长,如果你是高手请您读一读,能对其中的一些误点提出来,以免我误人子弟,并且帮助我提高 如果你是javascript菜

兼容安卓和ios实现一键复制内容到剪切板

实现代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="renderer" content="webkit"> <m

Android、IOS浏览器的适配问题整理

相关知识点: 移动端. 兼容/适配 . IOS点击事件300ms延迟 .点击穿透 . 定位失败 ... 手机浏览器特有的事件: onTouchmove . ontouched . ontouchstart . ontouchcancel. 使用Zepto的原因: jQuery适用于PC端桌面环境,桌面环境更加复杂,jQuery需要考虑的因素非常多,尤其表现在兼容性上面. 与PC端相比,移动端的发展远不及PC端,手机上的带宽永远比不上pc端. pc端下载jQuery到本地只需要1~3秒(90+K)

Android &amp;Swift iOS开发:语言与框架对比

转载自:http://www.infoq.com/cn/articles/from-android-to-swift-ios?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&utm_content=link_text 从Android到Swift iOS开发:语言与框架对比 我从2009年开始做Android开发,开始接触Swift是在2014年底,当时组里曾经做过一个Demo App,感觉技术还