input框輸入金額完美交互


交互內容:

輸入前顯示“0.00”
移入后如果是“0.00”則清空內容
移入后如果是“*.00”則去除后面的“.00”以方便填寫
移入后如果是“*.*0”則優化成“*.*”,即去掉最后面的“0”以方便填寫
什么都沒寫移出后又再次填充“0.00”
只能輸入數字和小數點
僅能輸入一個小數點
僅保留后面兩個小數點

 1 <div class="mui-input-row">
 2     <label>金額<span>(元)</span></label>
 3     <input type="tel" class="capital mui-input-clear" value="0.00">
 4 </div>
 5 
 6 <style>
 7 *{
 8     font-family:'microsoft yahei';
 9     height:30px;
10     line-height:30px;
11 }
12 input{
13     width:100px;
14     border-radius:.3em;
15     border:1px solid #ccc;
16     padding-left:.5em;
17     margin-left:.3em;
18 }
19 </style>

 js部分:

 1 /*投資本金僅能輸入數字和小數點*/
 2 var precapital;
 3 document.querySelector('.capital').addEventListener('focus', function() {
 4     if (this.value == '0.00') {
 5         this.value = '';
 6     } else {
 7         this.value = this.value.replace(/\.00/, '').replace(/(\.\d)0/,'$1');
 8     }
 9     precapital = this.value;
10 });
11 document.querySelector('.capital').addEventListener('keyup', function() {
12 
13     this.value = this.value.replace(/^[\.]/, '').replace(/[^\d.]/g, '');
14     if (this.value.split(".").length - 1 > 1) {
15         this.value = precapital;
16     }
17     precapital = this.value;
18 });
19 document.querySelector('.capital').addEventListener('blur', function() {
20     this.value = this.value.replace(/[\.]$/, '');
21     this.value = this.value.replace(/(.*)\.([\d]{2})(\d*)/g,'$1.$2');
22     this.value = Number(this.value).toFixed(2);
23     var logNum = this.value.toString();
24     if(logNum.match(/\./g) != null){
25         integerNum = parseInt(logNum).toString().replace(/\d(?=(\d{3})+$)/g,'$&,');
26         decimalNum = '.' + logNum.replace(/(.*)\.(.*)/g,'$2');
27         document.querySelector(".logbox").innerHTML = integerNum+decimalNum;
28     }else{
29         document.querySelector(".logbox").innerHTML = logNum.replace(/\d(?=(\d{3})+$)/g,'$&,');
30     }
31 });

請使用手機"掃一掃"x


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM