How can I add a Javascript listener to capture inp

2020-01-31 12:17发布

问题:

I'm having trouble logging keystrokes in javascript on the iPad. The following script works on Chrome and Safari, but not iPad Safari. The bluetooth barcode scanner sends 12 digits as keystrokes, then sends a return character. Does anyone have any ideas?

I think you will need an iPad to try this out :)

Thanks, Mark

$(document).ready(function(){
 $(document).keypress(function(e){
  if( e.keyCode == 13){
   alert($('#barcode').attr('value'));
   $('#barcode').attr('value','');
  }
  else{
   var key = String.fromCharCode(e.which);
   var new_val = $('#barcode').attr('value') + key;
   $('#barcode').attr('value',new_val);
  }
 });
});

回答1:

Safari for iOS doesn't trigger keyboard events on DOM elements that are not components of a form. This includes the document and body which are usually used to capture keystrokes anywhere on the page.

The only way to trigger a keystroke event on document or body of a page is to trigger it in an input or textarea. In that case, the event will correctly 'bubble' to the body and document.

However, this might be a problem because Safari for iOS doesn't allow us to give an element focus from javascript.

At the moment, we are using a solution where user has to click on an input field before starting the first scan, and the input field is then moved off-screen but retains focus.

If someone has a better solution, please share.



回答2:

Hello try to use this that work only with the "Prototype" javascript framework. This script work only with EAN13 or EAN8, but if you want to works with 12 digit just change the "if(result.lenght == 13)".

<script language="javascript" type="text/javascript">

    Event.observe(window, 'load', function(){
        Event.observe(document, 'keyup', myEventHandler);
    });

    var timeout = 0;

    function myEventHandler(e)
    {
        if(e.keyCode == 13)
        {
            var result = $('test').value;
            $('test').value = '';

            if(result.length == 13 || result.length == 8)
            {
                var d = new Date();
                var interval = d.getTime() - timeout;
                timeout = 0;

                if(interval <= 1000)
                {
                    alert(result);
                }
            }
        }
        else if(e.keyCode >= 48 && e.keyCode <= 57)
        {
            if(timeout == 0)
            {
                var d = new Date();
                timeout = d.getTime();
            }

            var key = String.fromCharCode(e.which);
            var new_val = $('test').value + key;
            $('test').value = new_val;
        }
    }
</script>
<input type="hidden" id="test" />