简体   繁体   中英

Close IOS keyboard in Safari with Javascript/AngularJS without .blur()

My problem: I need to close the IOS keyboard when an HTML form is submitted using the return button in Safari mobile. All solutions I can find for this problem say that using element.blur() should close the keyboard, so I made an Angular directive to do just that. However, it doesn't seem to work unless Done is pressed instead. Some examples of what I've tried:

form.on('submit', function () {
  var textfields = form.find('input');
  textfields[0].blur();
});



form.on('submit', function () {
  var textfields = form.find('input');
  textfields[0].focus();
  textfields[0].blur();
})



var defocusElement = angular.element('<input style="opacity: 0; width: 0" type="button">');

form.append(defocusElement);

form.on('submit', function () {
  defocusElement.focus();
})

Could someone recommend another avenue I can try? All these solutions work fine for Android.

Check for an onKeyUp event with keyCode 13(return key) and close the event.

<input type="text" onkeyup="closeKeyboard(event)">

closeKeyboard:

var closeKeyboard = function(event){
    if(event.keyCode == 13)
         //code to close the keyboard
}

This will work if for some reason element.blur() is not working:

function directive(_) {
   var directive = {
      restrict: 'A',
      link: function (scope, element) {
        var defocusElement = angular.element('<input style="opacity: 0; width: 0" type="button">');

        element.append(defocusElement);

        // Close keyboard on submit.
        element.on('submit', function () {
          defocusElement.focus();
        });

        // Handles return key on IOS Safari keyboard.
        element.on('keyup', function (event) {
          if(event.keyCode === 13) {
            defocusElement.focus();
          }
        });
      }
    };

    return directive;
  }

Thanks ayushgp!

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