html keycodes not working in firefox

后端 未结 3 668
旧时难觅i
旧时难觅i 2021-01-21 18:59

I have the following code:

function noNumbers(e)
{
    var charCode = (e.which) ? e.which : 
                 ((e.charCode) ? e.charCode : 
                   ((         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-21 19:28

    This works for me on Firefox.

    var keycodes = {
        'backspace': 8,
        'delete': 46,
        'leftArrow': 37,
        'rightArrow': 39,
        'number1': 48,
        'number9': 57
    };
    
    function noNumbers(e)
    {
        var charCode = e.which ? e.which : 
                     (e.charCode ? e.charCode : 
                       (e.keyCode ? e.keyCode : 0));
        
        if ((charCode < keycodes.number1 || charCode > keycodes.number9) &&
            charCode !== keycodes.delete &&
            charCode !== keycodes.backspace &&
            charCode !== keycodes.leftArrow &&
            charCode !== keycodes.rightArrow)
            e.preventDefault();
    }
    
    document.getElementById('noNum').addEventListener(
    	'keypress', noNumbers
    );

提交回复
热议问题