hide keyboard in iphone safari webapp

后端 未结 9 1888
长情又很酷
长情又很酷 2020-12-13 13:40

I\'m creating a webapp for the iPhone, based in HTML/CSS/JS. I\'m using forms to receive input and pass data to the script, but a problem I\'m encountering is that the keybo

9条回答
  •  别那么骄傲
    2020-12-13 13:56

    I came across this issue and have spent some time until getting a satisfactory solution. My issue was slightly different from the original question as I wanted to dismiss the input event upon tapping outside input element area.

    The purposed answers above work but I think they are not complete so here is my attempt in case you land this page looking for the same thing I was:

    jQuery solution

    We append a touchstart event listener to the whole document. When the screen is touched (doesn't matter if it's a tap, hold or scroll) it will trigger the handler and then we will check:

    1. Does the touched area represent the input?
    2. Is the input focused?

    Given these two conditions we then fire a blur() event to remove focus from the input.

    ps: I was a little bit lazy so just copied the line from above response, but you can use the jQuery selector for document in case you want to keep consistency of code

    $(document).on('touchstart', function (e) {
      if (!$(e.target).is('.my-input') && $('.my-input').is(':focus')) {
        document.activeElement.blur();
      }
    });
    

    Hammer.JS solution

    Alternatively you can use Hammer.JS to handle your touch gestures. Let's say that you want to dismiss that on a tap event but the keyboard should be there if the users is just scrolling the page (or let's say, hold a text selection so he can copy that and paste into your input area)

    In that situation the solution would be:

    var hammer = new Hammer(document.body);
    hammer.on('tap', function(e) {
      if (!$(e.target).is('.search-input') && $('.search-input').is(':focus')) {
        document.activeElement.blur();
      }
    });
    

    Hope it helps!

提交回复
热议问题