Blogger Information
Blog 34
fans 0
comment 0
visits 26564
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js 计算器模拟
罗盼的博客
Original
704 people have browsed it

计算器模拟

实例

<!DOCTYPE HTML>
<html>
<head>
	<meta http-equiv="content-type" content="text/html" charset="utf-8"/>
	<style>
    .comp{
    width: 500px; 
    min-height: 200px;   
    box-shadow: 3px 3px 3px gray;
    margin: 0 auto; 
    border: 1px solid #efefef;  
    padding: 20px 100px; 
    background: gray;
    border-radius: 5px;  
    }
    
    #input1{
     margin: 10px 0 ;   
    }
    
    
    
    </style>

	<title>计算器模拟</title>
</head>

<body>
<div class="comp">
<form>
<input type="text" name="input1"  id="input1" />

<select id="tag">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>

<input type="text" name="input2" id="input2"  />
<button type="button" >计算</button>
</form>
<p >结果:</p>
<p id="result"></p>
</div>

<script>
//获取按钮
    let btn = document.getElementsByTagName("button")[0];
    let input1 = document.getElementById('input1');
    let input2 = document.getElementById('input2');
    let tags = document.getElementById('tag');
    let p = document.getElementById('result');
    
btn.onclick = function (){
   
 
    let num1 = 0;
    let num2 = 0;
    let tag  = tags.value;
    result = 0;
     
     //非空判断/数据字符串解析处理
     if(input1.value.length===0){
        alert('第一个数不能为空');
        input1.focus();
        return false;
     }else if(isNaN(input1.value)){
        alert('第一个数字符');
        input1.focus();
        return false;
     }else if(input2.value.length===0){
        alert('第一个数不能为空');
        input1.focus();
        return false;
     }else if(isNaN(input2.value)){
        alert('第一个数字符');
        input1.focus();
        return false;
     }else{
        num1 = parseFloat(input1.value);
        num2 = parseFloat(input2.value);
     }
     
     
    //数据运算
    if(tag==='+'){       
       result = num1+num2;               
    }else if(tag==='-'){
       result = num1-num2;
    }else if(tag==='*'){
       result = num1*num2; 
    }else{
        if(num2===0)
        {
            alert('除数不能为0');
            num2='';
            return false;  
        }
       result = num1/num2;
    }
    
p.innerHTML= result;
}


</script>

</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments