需求:根据素材制作如图所示页面,在页面输入第一个数和第二个数,单击+(加)、-(减)、*(乘)、/(除)按钮时,实现两个数的相应运算
Code
< ! DOCTYPE html>
< html lang= "en" > < head> < meta charset= "UTF-8" > < meta name= "viewport" content= "width=device-width, initial-scale=1.0" > < title> Calculator< / title> < style> . btn- spacing { margin- right: 24px; } button { width : 40px; height : 20px; } < / style>
< / head> < body> < ! -- 输入框用于输入两个数字 -- > < label for = "num1" > 第一个数 < / label> < input type= "number" id= "num1" > < br> < br> < label for = "num2" > 第二个数 < / label> < input type= "number" id= "num2" > < br> < br> < ! -- 按钮用于执行加法、减法、乘法和除法运算 -- > < button onclick= "add()" class = "btn-spacing" > + < / button> < button onclick= "subtract()" class = "btn-spacing" > - < / button> < button onclick= "multiply()" class = "btn-spacing" > * < / button> < button onclick= "divide()" > / < / button> < br> < br> < ! -- 显示结果的文本框 -- > < label for = "result" > 计算结果 < / label> < input type= "text" id= "result" readonly> < script> function add ( ) { var num1 = parseFloat ( document. getElementById ( "num1" ) . value) ; var num2 = parseFloat ( document. getElementById ( "num2" ) . value) ; var result = num1 + num2; document. getElementById ( "result" ) . value = result; } function subtract ( ) { var num1 = parseFloat ( document. getElementById ( "num1" ) . value) ; var num2 = parseFloat ( document. getElementById ( "num2" ) . value) ; var result = num1 - num2; document. getElementById ( "result" ) . value = result; } function multiply ( ) { var num1 = parseFloat ( document. getElementById ( "num1" ) . value) ; var num2 = parseFloat ( document. getElementById ( "num2" ) . value) ; var result = num1 * num2; document. getElementById ( "result" ) . value = result; } function divide ( ) { var num1 = parseFloat ( document. getElementById ( "num1" ) . value) ; var num2 = parseFloat ( document. getElementById ( "num2" ) . value) ; if ( num2 === 0 ) { document. getElementById ( "result" ) . value = "Cannot divide by zero!" ; } else { var result = num1 / num2; document. getElementById ( "result" ) . value = result; } } < / script> < / body> < / html>
效果