简体   繁体   中英

Mobile Safari - Dismiss Keyboard with Javascript

I'm trying to dismiss the keyboard via JS in response to a button press, but I'm not having any luck.

Setup:

  1. I have a textarea with accept and cancel buttons tied to it.
  2. Upon clicking the cancel button, my view object will call textAreaElement.blur() .
  3. It will then remove the accept and cancel buttons.

Expected:

  • Field loses focus (visually and otherwise).
  • Keyboard is dismissed.

Actual:

  • Field appears to lose focus (visually, no cursor is displayed), and programmatically.
  • Keyboard is still presented.

I've already tried the usual Google but they all seem to think that calling blur on the focused element should be sufficient. One user even suggested calling $('input').blur() to ensure that all fields were blurred, but that didn't seem to make a difference.

... and I just figured out why this was happening.

I mentioned that I was removing the Accept and Cancel buttons for this field. Specifically the following was taking place:

  1. Call textAreaElement.blur() .
  2. Animate the buttons disappearing.
  3. Upon completion of the animation, buttons.remove() .

When the Cancel button received the click, it gained focus (the keyboard remained active). When the Cancel button was subsequently removed in the animation completion callback, focus was applied to the previous focusable element, which is the textarea .

So I had the effect of doing:

textarea.blur() # Already doesn't have focus. buttons.remove() # Removes buttons, applies their focus back to the textarea.

The solution was to instead:

  1. Animate the buttons disappearing.
  2. Wait for completion of the animation, buttons.remove() .
  3. Call textAreaElement.blur() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM