input 只允许输入0-100且保留两位小数

248 阅读1分钟
<input class="markInput" type="text" maxlength="6" oninput="inputChange.call(this)" onblur="inputBlur.call(this)">
      function inputChange() {
        this.value = this.value.replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
          .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
          .replace(/^\./g, '')

        if (this.value.indexOf('.') < 0 && this.value !== '') {
          this.value = parseFloat(this.value) + ''
        }
        if (this.value > 100) {
          this.value = 100
        }
      }
      
      function inputBlur() {
        if (this.value.charAt('0') == 0) {
          this.value = this.value.replace(/\b(0+)/gi, ""); // 清除多余的'0'
        }
        if (this.value.indexOf('.') < 0) {
          if (!this.value) {
            this.value += '0.00'
          } else {
            this.value += '.00'
          }
        } else {
          const numDian = this.value.split('.')[1].length;
          if (numDian === 1) {
            this.value += '0';
          } else if (numDian === 0) {
            if (this.value !== '.') {
              this.value += '00';
            } else {
              this.value = '0.00'
            }
          }
        }
      }