JQuery将输入掩码应用于字段onfocus并删除onblur,以避免占位符文本出现问题 [英] JQuery apply input mask to field onfocus and remove onblur so to avoid problems with placeholder text

查看:60
本文介绍了JQuery将输入掩码应用于字段onfocus并删除onblur,以避免占位符文本出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a date of birth text field:

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

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

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.

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

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/).

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

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

我需要类似的东西:

$(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?

推荐答案

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

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);

注意我添加了(function($){})(jQuery) - 我相信它很好练习以这种方式包装所有代码。

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

这篇关于JQuery将输入掩码应用于字段onfocus并删除onblur,以避免占位符文本出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆