返回

点击非输入框收起键盘,一行代码搞定!

Android

很多手机系统都支持在点击非输入框区域收起键盘的功能,这不仅使APP的操作更方便,也为用户提供了更好的体验。在iOS和安卓系统中,都支持通过设置isTextField为true的方式来禁用键盘弹出。而Flutter和JS等开发框架则提供了专门的库函数,如closeKeyboard()和document.activeElement.blur()来关闭键盘。最后,介绍了一种利用HTML的CSS样式来隐藏键盘的方法。
让我们一起来看看如何使用一行代码实现点击非输入框收起键盘功能吧!

iOS开发

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

安卓开发

EditText editText = (EditText) findViewById(R.id.editText);
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
});

Flutter开发

final FocusNode focusNode = FocusNode();

@override
Widget build(BuildContext context) {
  return GestureDetector(
    onTap: () {
      focusNode.unfocus();
    },
    child: TextField(
      focusNode: focusNode,
    ),
  );
}

JS开发

const input = document.getElementById('input');

input.addEventListener('blur', () => {
  document.activeElement.blur();
});

HTML开发

<style>
  body {
    overflow: hidden;
  }

  input {
    position: absolute;
    top: -100vh;
  }
</style>

<input type="text">