1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| <div class="pwGenBox"> <button onclick="generate()">生成密码</button> <input id="hasSpec" type="checkbox" /> <p>特殊字符</p> <h3 class="password"></h3> <input class="input" style="opacity:0;position:absolute;top:-999px;" /> <button onclick="copy()">点击复制</button> </div> <script> var input; function copy() { input.select(); document.execCommand("Copy"); } function generate() { let hasSpec = document.querySelector("#hasSpec").checked; let len = 14; str = randomStr(len, hasSpec); let pwd = document.querySelector("h3.password"); input = document.querySelector("input.input"); input.value = str; pwd.innerText = str; } function randomStr(len, hasSpec = false) { let str = ""; while (str.length < len) { switch (Math.floor(Math.random() * 4)) { case 0: str += num(); break; case 1: str += upper(); break; case 2: str += lower(); break; case 3: if (hasSpec) { str += spec(); } break; default: str += "?"; break; } } return str; } function _randomASCII(start, span) { return String.fromCharCode(Math.floor(Math.random() * span + start)); } function upper() { return _randomASCII(65, 26); } function lower() { return _randomASCII(97, 26); } function num() { return _randomASCII(48, 10); } function spec() { return _randomASCII(33, 14); } </script> <style> .pwGenBox p { display: inline-block; } </style>
|
input框如果设置为display:none会导致无法选中,可以选择移动到屏幕外/设置透明/被遮盖的方法掩藏,或者写一些css让input框代替展示文本。