You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复intlTelInput插件的Placeholder显示异常问题?

解决intlTelInput与jQuery Mask切换国家时占位符异常问题

问题现象

使用intlTelInput插件结合jQuery Mask实现手机号输入时,切换国家选项后出现占位符显示异常:

  • 初始选择巴西时,占位符为(11) 96123-4567
  • 切换至博茨瓦纳等其他国家后再切回巴西,占位符变为(11) 96123,缺失末尾的-4567部分

问题演示

问题原因

  1. 插件占位符逻辑冲突:intlTelInput默认开启的autoPlaceholder功能会与jQuery Mask的占位符生成逻辑互相干扰,导致占位符被截断
  2. mask生成格式错误:原代码使用国际格式的示例号码生成mask,国际区号部分会干扰本地号码的mask规则,且未清除旧mask就叠加新规则,导致规则异常

修复方案

通过调整插件配置和mask生成逻辑解决冲突,以下是修复后的完整代码:

HTML 代码

<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/intlTelInput.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/css/intlTelInput.css" rel="stylesheet" />
</head>
<body>
  <input type="tel" id="phone" name="phone" />
</body>
</html>

JavaScript 代码

$(document).ready(function() {
  var phoneInputID = "#phone";
  var input = document.querySelector(phoneInputID);
  var iti = window.intlTelInput(input, {
    formatOnDisplay: true,
    initialCountry: "BR",
    hiddenInput: "full_number",
    preferredCountries: ['es'],
    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.14/js/utils.js",
    autoPlaceholder: "off" // 禁用intlTelInput自动占位符,避免冲突
  });

  $(phoneInputID).on("countrychange", function(event) {
    var selectedCountryData = iti.getSelectedCountryData();
    
    // 获取本地格式的示例号码,适配本地输入习惯
    var exampleNumber = intlTelInputUtils.getExampleNumber(
      selectedCountryData.iso2, 
      true, 
      intlTelInputUtils.numberFormat.NATIONAL
    );

    // 清除之前的mask规则,避免残留干扰
    $(this).unmask();
    // 重置输入框内容
    iti.setNumber("");

    // 将示例号码转换为mask规则:数字替换为0,保留格式符号
    var mask = exampleNumber.replace(/[1-9]/g, "0");

    // 应用新mask并手动设置占位符
    $(this).mask(mask);
    $(this).attr("placeholder", exampleNumber);
  });

  // 初始化时触发一次事件,设置初始mask和占位符
  iti.promise.then(function() {
    $(phoneInputID).trigger("countrychange");
  });
});

关键修改说明

  • 关闭intlTelInput自动占位符:添加autoPlaceholder: "off",将占位符控制权完全交给jQuery Mask
  • 使用本地格式示例号:通过numberFormat.NATIONAL获取符合本地习惯的示例号码,避免国际区号干扰
  • 先清除旧mask再应用新规则:切换国家时执行unmask(),确保mask规则是全新的
  • 手动设置占位符:直接将示例号码设为input的placeholder,保证显示内容完整准确

内容的提问来源于stack exchange,提问作者Michel Galvão

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 11:25:30