实现代码
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 | <!doctype html> < html > < head > < meta charset = "utf-8" > < title >JS+CSS3实现计算器特效</ title > < link type = "text/css" rel = "stylesheet" href = "css/datouwang.css" /> </ head > < body > < div id = "calculator" > <!-- Screen and clear key --> < div class = "top" > < span class = "clear" >C</ span > < div class = "screen" ></ div > </ div > < div class = "keys" > <!-- operators and other keys --> < span >7</ span > < span >8</ span > < span >9</ span > < span class = "operator" >+</ span > < span >4</ span > < span >5</ span > < span >6</ span > < span class = "operator" >-</ span > < span >1</ span > < span >2</ span > < span >3</ span > < span class = "operator" >÷</ span > < span >0</ span > < span >.</ span > < span class = "eval" >=</ span > < span class = "operator" >x</ span > </ div > </ div > < script src = "js/datouwang.js" type = "text/javascript" ></ script > </ body > </ html > |
js
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 | var keys = document.querySelectorAll( '#calculator span' ); var operators = [ '+' , '-' , 'x' , '÷' ]; var decimalAdded = false ; for ( var i = 0; i < keys.length; i++) { keys[i].onclick = function (e) { var input = document.querySelector( '.screen' ); var inputVal = input.innerHTML; var btnVal = this .innerHTML; if (btnVal == 'C' ) { input.innerHTML = '' ; decimalAdded = false ; } else if (btnVal == '=' ) { var equation = inputVal; var lastChar = equation[equation.length - 1]; equation = equation.replace(/x/g, '*' ).replace(/÷/g, '/' ); if (operators.indexOf(lastChar) > -1 || lastChar == '.' ) equation = equation.replace(/.$/, '' ); if (equation) input.innerHTML = eval(equation); decimalAdded = false ; } else if (operators.indexOf(btnVal) > -1) { var lastChar = inputVal[inputVal.length - 1]; if (inputVal != '' && operators.indexOf(lastChar) == -1) input.innerHTML += btnVal; else if (inputVal == '' && btnVal == '-' ) input.innerHTML += btnVal; if (operators.indexOf(lastChar) > -1 && inputVal.length > 1) { input.innerHTML = inputVal.replace(/.$/, btnVal); } decimalAdded = false ; } else if (btnVal == '.' ) { if (!decimalAdded) { input.innerHTML += btnVal; decimalAdded = true ; } } else { input.innerHTML += btnVal; } e.preventDefault(); } } |
特别申明:
本站所有资源都是由网友投稿发布,或转载各大下载站,请自行检测软件的完整性!
本站所有资源仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您自己承担!
如有侵权请联系我们删除下架,联系方式:lei1294551502@163.com