以下是一个使用 HTML、JavaScript 实现生成指定长度的随机字符串,并满足上述要求的示例代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>随机字符串生成器</title> </head> <body> <h2>随机字符串生成器</h2> <input type="text" id="userInput" placeholder="输入您的特定字符"> <input type="number" id="lengthInput" placeholder="输入字符串长度"> <button onclick="generateRandomString()">生成</button> <div id="result"></div> <button onclick="copyToClipboard()">复制</button> <script> function generateRandomString() { let userChar = document.getElementById('userInput').value; let length = parseInt(document.getElementById('lengthInput').value); let allChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + userChar; let result = ''; let upperCaseCount = 0; let lowerCaseCount = 0; let digitCount = 0; let userCharCount = 0; while (result.length < length) { let randomChar = allChars.charAt(Math.floor(Math.random() * allChars.length)); result += randomChar; if (/[A-Z]/.test(randomChar)) { upperCaseCount++; } else if (/[a-z]/.test(randomChar)) { lowerCaseCount++; } else if (/[0-9]/.test(randomChar)) { digitCount++; } else if (userChar.includes(randomChar)) { userCharCount++; } if (upperCaseCount >= 2 && lowerCaseCount >= 2 && digitCount >= 2 && userCharCount >= 2) { break; } } document.getElementById('result').innerHTML = result; } function copyToClipboard() { let result = document.getElementById('result').innerHTML; navigator.clipboard.writeText(result).then(() => { alert('已复制到剪贴板'); }, () => { alert('复制失败'); }); } </script> </body> </html> ``` 对于生成较长字符串时减少卡顿的问题,可以考虑以下几点: 1. 采用分段生成和拼接的方式,而不是一次性生成整个字符串。 2. 在生成过程中,适时更新界面显示已生成的部分字符串,让用户感觉到有进展,而不是长时间的等待。 3. 对于非常长的字符串,可以提示用户生成可能需要较长时间,并建议适当减小长度。 [2024-11-07 17:50:36 | AI写代码神器 | 677点数解答]