欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  最近在准备专升本,抽一点时间敷衍一下大家!!!嘿嘿嘿!!!
 
  话不多说,上代码:
 
  <!DOCTYPEhtml>
 
  <htmllang="zh-CN">
 
  <head>
 
  <metacharset="utf-8">
 
  <title>求和练习</title>
 
  <styletype="text/css">
 
  *{
 
  margin:0;
 
  padding:0;
 
  }
 
  .cal-sum{
 
  width:500px;
 
  margin:100pxauto;
 
  }
 
  .cal-suminput{
 
  width:200px;
 
  height:20px;
 
  padding:05px;
 
  margin-right:5px;
 
  }
 
  .cal-sumbutton{
 
  margin-top:30px;
 
  width:100px;
 
  height:20px;
 
  }
 
  .cal-sump{
 
  margin-top:30px;
 
  font-size:30px;
 
  color:red;
 
  }
 
  </style>
 
  <scripttype="text/javascript">
 
  window.onload=()=>{
 
  constsumInput=document.getElementById('sum_input');
 
  constsumBtn=document.getElementById('sum_btn');
 
  constsumValue=document.getElementById('sum_value');
 
  //确保输入框只能输入半角‘,’和数字
 
  //keyup事件,键盘抬起事件
 
  sumInput.addEventListener('keyup',()=>{
 
  sumInput.value=sumInput.value.replace(/[^(\d)|(,)]/,"");
 
  });
 
  sumBtn.addEventListener('click',()=>{
 
  letsum=0;
 
  letinputNum=sumInput.value.split(',');
 
  for(letnumininputNum){
 
  sum+=parseInt(inputNum[num]);
 
  }
 
  sumValue.innerHTML=sum;
 
  });
 
  }
 
  </script>
 
  </head>
 
  <body>
 
  <divclass="cal-sum">
 
  <div><inputtype="text"value="1,2,3,4,5,6"id="sum_input"><span>求数字之和,数字之间用半角‘,’分隔</span></div>
 
  <buttonid="sum_btn">求和</button>
 
  <p><strongid="sum_value"></strong></p>
 
  </div>
 
  </body>
 
  </html>
 
  [注]在正则表达式中,^在[]中代表否定,在这个练习中意思就是:只要不是^和数字,当键盘输入抬起后,会自动替换为没有,现象即自动会退回
 
  放假了,也要抽点时间学习呀~~~~

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h56583.shtml