【问题标题】:I cant make inputmask to work with vanilla JS我无法让 inputmask 与 vanilla JS 一起使用
【发布时间】:2022-03-02 00:11:54
【问题描述】:

我想在没有加载 jquery 的情况下使用 inputmask 并直接在带有 vanilla JS 的浏览器中使用。但它似乎总是需要 jQuery:

var selector = document.getElementById("gg");
Inputmask({mask:"9999"}).mask(selector);
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/inputmask.min.js"></script>
<input type="text" id="gg">

(打开控制台,你会看到Uncaught ReferenceError: $ is not defined

有什么想法吗?

【问题讨论】:

  • 这个错误好像你没有正确加载jQuery - 如果你正在使用它?确保您在页面标题中添加了jQuery CDN,以便加载。
  • @AlwaysHelping 那个小提琴使用 jquery
  • 我的问题是我不想使用 jquery
  • 我从来没有说过没有jQuery
  • 是的,但我的问题是关于没有 jquery 的输入掩码

标签: javascript input-mask


【解决方案1】:

您使用的版本 (5.x5.0.4) 处于测试阶段,因此它可能已损坏(确实如此)。您应该使用最新的稳定版本,截至目前为 5.0.3

var selector = document.getElementById("gg");
Inputmask({mask:"9999"}).mask(selector);
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.0.3/dist/inputmask.min.js"></script>
<input type="text" id="gg">

【讨论】:

    【解决方案2】:

    在搜索了一段时间后,我决定自己编写代码,它完美地满足了我的需求:

    // Element constants
    const maskedInputs = document.querySelectorAll('input[data-mask]')
    
    // Base configuration for all masked inputs
    for (const input of maskedInputs) {
      // Get the input's mask
      let mask = input.getAttribute('data-mask')
      // Get the input's mask reverse boolean
      const reverse = input.getAttribute('data-mask-reverse') !== null
      // Stores a boolean value to indicate if the mask ends with a numeric character
      const maskEndsWithNumber = !isNaN(mask.charAt(mask.length - 1))
    
      // If the data-mask-reverse attribute exists, reverse the mask string
      if (reverse) {
        mask = [...mask].reverse().join('')
      }
    
      // Separate the numeric parts from the mask
      const numericParts = mask.split(/[^\d]/g).filter(part => !!part.length)
      // Add the regex format to all parts
      const regexParts = numericParts.map(m => `([\\d#]\{${m.length}\})`)
      // Join the regex parts to create the final regex
      const maskRegex = new RegExp(regexParts.join(''))
      // Calculates the full length of numeric characters
      const fullLength = numericParts.join('').length
      // Initiates the group counter
      let i = 1
      // Creates the group mask string
      const maskReplace = mask.replace(/\d{1,}/g, () => `\$${i++}`)
    
      // Set the input's max length to the size of the mask
      input.setAttribute('maxlength', mask.length)
    
      // Function to handle the input events
      function maskHandler(e) {
        // Get the input's current value
        let { value } = input
    
        // Removes the last character if the user deleted the last non-numeric character
        if (e.type === 'keydown' && e.keyCode == 8 && isNaN(value.charAt(value.length - 1))) {
          value = value.replace(/\d[^\d]{1,}$/, '')
          e.preventDefault()
        }
    
        // Removes all non-numeric characters from it
        value = value.replace(/[^\d]/g, '')
    
        // Reverse the string if needed
        if (reverse) {
          value = [...value].reverse().join('')
        }
    
        // Fill the string with '#'
        value = value.padEnd(fullLength, '#')
        // Apply the mask
        value = value.replace(maskRegex, maskReplace)
    
        // Get the end of the numeric part (start of the '#' fill)
        const fillIndex = value.indexOf('#')
        // Checks if the fill character exists
        if (fillIndex !== -1) {
          // Remove the '#' fill
          value = value.slice(0, fillIndex)
        }
    
        // Assures the string ends with a numeric character
        if (maskEndsWithNumber) {
          value = value.replace(/[^\d]$/, '')
        }
        // Restore the right order of the string
        if (reverse) {
          value = [...value].reverse().join('')
        }
    
        // Update the input's value
        input.value = value
      }
    
      // Handles the onkeyup, keydown and change events on the masked input
      input.addEventListener('keyup', maskHandler)
      input.addEventListener('keydown', maskHandler)
      input.addEventListener('change', maskHandler)
    }
    

    这使得每个具有“data-mask”属性的输入元素都会自动应用指定的掩码。我包含的另一个属性是“data-mask-reverse”,它是一个布尔属性,当您需要值来反向填充掩码时(我将其用于货币值):

    <!-- Mask example -->
    <input type="text" data-mask="9999/9999">
    <!-- Reversed mask example -->
    <input type="text" data-mask="999,999,999.99" data-mask-reverse>
    

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2023-03-30
      • 1970-01-01
      • 2018-04-22
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多