javascript JQuery 将输入掩码应用于字段 onfocus 并删除 onblur 以避免占位符文本出现问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4816511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:57:36  来源:igfitidea点击:

JQuery apply input mask to field onfocus and remove onblur so to avoid problems with placeholder text

javascriptjquery

提问by Paul

I have a date of birth text field:

我有一个出生日期文本字段:

<input type="text" id="dob" name="dob" placeholder="Date of Birth" />

I'm using a jQuery plugin (Charl van Niekerk's Placeholder text) to make sure that older browsers see the placeholder text. All good so far.

我正在使用 jQuery 插件(Charl van Niekerk 的占位符文本)来确保旧浏览器看到占位符文本。到目前为止一切都很好。

When my date of birth field is clicked on, I want to switch from the placeholder text to an input mask. For that I'm using another plugin (http://digitalbush.com/projects/masked-input-plugin/).

当我的出生日期字段被点击时,我想从占位符文本切换到输入掩码。为此,我正在使用另一个插件(http://digitalbush.com/projects/masked-input-plugin/)。

However I only want to activate the input mask onfocus, and remove it onblur, otherwise it stops the placeholder text from being shown.

但是我只想激活输入掩码 onfocus,并将其删除 onblur,否则它会停止显示占位符文本。

I need something like:

我需要类似的东西:

$(document).ready(function() {    
    $('#dob').focus(function() {  
        $.mask.definitions['~']='[+-]';
        $('#dob').mask('99/99/9999');  
    });
    $('#dob').blur(function() {
        // Something here to unmask?   
    });  
});

This code doesn't work at the moment. Any ideas?

此代码目前不起作用。有任何想法吗?

回答by Paul Spencer

Reading the plugin code, it should be possible to do this (untested):

阅读插件代码,应该可以做到这一点(未经测试):

(function($) {
  $(document).ready(function() {
    $('#dob').focus(function() {
      $.mask.definitions['~']='[+-]';
      $(this).mask('99/99/9999');
    }).blur(function() {
      $(this).unmask();
    });
  });
})(jQuery);

Note that I added (function($){})(jQuery) - I believe it is good practice to wrap all your code this way.

请注意,我添加了 (function($){})(jQuery) - 我相信以这种方式包装所有代码是一种很好的做法。