在 iOS 上的 Safari 和 Chrome 中只允许使用数字和冒号



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

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

我们使用类似的逻辑(键码 48-75 和 96-105),它可以工作。 我还没有测试过你的示例代码,但是你的第一个if语句大量使用&&和没有括号的||让我有点担心。 也许尝试放入一些括号组并再试一次?

这是我最终要做的 - 检测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;

最新更新