jquery ?一鍵復制功能,兼容蘋果
有做過一個項目,做好之后交給客戶,客戶用的是蘋果手機,不料給我反饋回來一鍵復制功能 不能使用。
這是我原來的代碼
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
? ? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? ? <title>微信名片</title>
</head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<body>
? ? 微信: <input class="mytxt" id="xmid" value="13521423628" readonly="readonly" unselectable="on"></input>
? ? <span class="copyname">(點擊復制)</span>
? ? </div>
? ? </footer>
? ? </div>
? ? <script>
? ? ? ? // 一鍵復制 只針對安卓 select()不兼容蘋果
? ? ? ? $('.copyname').click(function () {
? ? ? ? ? ? var dd = $('.mytxt');
? ? ? ? ? ? dd[0].select();
? ? ? ? ? ? document.execCommand("Copy");
? ? ? ? ? ? alert("復制成功!")
? ? ? ? });
? ? </script>
</body>
</html>
對,這段代碼可以實現(xiàn)一鍵復制的效果,但值在安卓手機上生效,因為select()在蘋果上不生效。這也算是蘋果的一個坑吧。
所以換了一種寫法,兼容蘋果的,以后都用這個了,有需要的朋友可以看下
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
? ? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? ? <title>微信名片</title>
</head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<body>
? ? 微信: <input class="mytxt" id="xmid" value="13521423628" readonly="readonly" unselectable="on"></input>
? ? <span onClick="copyNum()">(點擊復制)</span>
? ? </div>
? ? </footer>
? ? </div>
? ? <script>
? ? ? ? // 思路:要想復制到剪貼板,必須先選中這段文字。
? ? ? ? function copyNum() {
? ? ? ? ? ? var NumClip = document.getElementById("xmid");
? ? ? ? ? ? var NValue = NumClip.value;
? ? ? ? ? ? var valueLength = NValue.length;
? ? ? ? ? ? selectText(NumClip, 0, valueLength);
? ? ? ? ? ? if (document.execCommand('copy', false, null)) {
? ? ? ? ? ? ? ? document.execCommand('copy', false, null) // 執(zhí)行瀏覽器復制命令
? ? ? ? ? ? ? ? alert("復制成功!");
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? alert("不兼容");
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? // input自帶的select()方法在蘋果端無法進行選擇,所以需要自己去寫一個類似的方法
? ? ? ? // 選擇文本。createTextRange(setSelectionRange)是input方法
? ? ? ? function selectText(textbox, startIndex, stopIndex) {
? ? ? ? ? ? if (textbox.createTextRange) { //ie
? ? ? ? ? ? ? ? var range = textbox.createTextRange();
? ? ? ? ? ? ? ? range.collapse(true);
? ? ? ? ? ? ? ? range.moveStart('character', startIndex); //起始光標
? ? ? ? ? ? ? ? range.moveEnd('character', stopIndex - startIndex); //結束光標
? ? ? ? ? ? ? ? range.select(); //不兼容蘋果
? ? ? ? ? ? } else { //firefox/chrome
? ? ? ? ? ? ? ? textbox.setSelectionRange(startIndex, stopIndex);
? ? ? ? ? ? ? ? textbox.focus();
? ? ? ? ? ? }
? ? ? ? }
? ? </script>
</body>
</html>