標籤:總結 head strong family abs doctype 字串 驗證 for
具體代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> body,div,ul,li{ margin:0; padding: 0; font-family: Arial; font-size:12px; -webkit-user-select:none; } #code{ width:100px; height:50px; line-height: 50px; text-align:center; border:1px solid #ff0000; cursor:pointer; top:50%; left:50%; position:absolute; margin-left:-50px; margin-top:-25px; letter-spacing: 3px } </style></head><body> <div id=‘code‘>xf2d</div> <script type=‘text/javascript‘> //設定隨機擷取的範圍 var codeStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //0-61索引,我只需要隨機產生4個索引,然後通過charAt就可以擷取到字元了 var oDiv = document.getElementById(‘code‘); //擷取隨機數 function getRandom(n,m){ n = Number(n); m = Number(m); if(isNaN(n) || isNaN(m)){ return Math.random() } if(n>m){ var temp = n; n = m; m = temp } return Math.round(Math.random()*(m-n)+n) } //擷取驗證碼 function getCode(){ var str = "" for(var i = 0;i<4;i++){ var ran = getRandom(0,61) str +=codeStr.charAt(ran); } oDiv.innerHTML = str; } getCode(); oDiv.onclick = function(){ getCode(); } </script></body></html>
js學習總結----字串和Math綜合應用-驗證碼(4位)