2012-12-19 48 views
1

我正在使用以下代码来防止将某些字符输入到文本框中。除了iPad和iPhone上的Chrome和Safari(webkit mobile?)之外,它工作正常。 Safari和Chrome在Mac上运行良好。任何想法如何限制为这些设备的数字和冒号?只允许iOS和Safari浏览器中的数字和冒号

jQuery.fn.forceNumeric = function (allowDecimal, allowColon) 
{ 
    return this.each(function() 
    { 
     $(this).keydown(function (e) 
     { 
      var key = e.which || e.keyCode; 

      if (!e.shiftKey && !e.altKey && !e.ctrlKey && 
      // numbers 
        key >= 48 && key <= 57 || 
      // Numeric keypad 
        key >= 96 && key <= 105 || 
      // period, comma, minus adn period on keypad 
      //  key == 190 || // period 
      //  key == 188 || // comma 
      //  key == 109 || // minus 
      //  key == 110 || // period on keypad 
      // Backspace and Tab and Enter 
        key == 8 || key == 9 || key == 13 || 
      // Home and End 
        key == 35 || key == 36 || 
      // left and right arrows 
        key == 37 || key == 39 || 
      // Del and Ins 
        key == 46 || key == 45) 
       return true; 
      else if (!e.shiftKey && !e.altKey && !e.ctrlKey && allowDecimal && key == 190) // period 
       return true; 
      else if (!e.shiftKey && !e.altKey && !e.ctrlKey && allowDecimal && key == 110) // period on keypad 
       return true; 
      else if (e.shiftKey && (key == 186 || key == 59) && allowColon) // colon (ie & chrome = 186, ff = 59) 
       return true; 
      else 
       return false; 
     }); 
    }); 

回答

1

我们使用类似的逻辑(keyCode 48-75和96-105),它的工作原理。我还没有测试过你的示例代码,但是你的第一个if声明是大量使用&&||而没有括号给我一点担心。也许尝试加入一些括号内的小组并再试一次?

+0

我发现,这是因为在iPad或iPhone上,您不必按Shift键访问冒号。但是如果我允许键186而不需要Shift,它允许用户输入一个分号,我想阻止它。 – Earl

+0

不是最干净的解决方案,但是您可以添加针对iphone/ipad的useragent的测试。像:e.shiftKey || (/(iPhone|iPod|iPad)/i.test(navigator.userAgent)) –

+0

是的,这就是我最终做的。 – Earl

0

这就是我最终做的 - 检测iOS设备并在原始脚本中添加一个else。有可能是更好的方法...

function isiPhone(){ 
    return (
     //Detect iPhone 
     (navigator.platform.indexOf("iPhone") != -1) || 
     //Detect iPod 
     (navigator.platform.indexOf("iPod") != -1) 
    ); 
} 

var isiPad = navigator.userAgent.match(/iPad/i) != null; 

... 
else if ((isiPhone() || isiPad) && (key == 186 || key == 59) && allowColon) // colon (iOS devices don't have a shift key) 
       return true; 
相关问题