简体   繁体   English

点击屏幕时iphone键盘不会隐藏

[英]iphone keyboard not hiding when tapping the screen

I have an input field with number type 我有一个数字类型的输入字段

<input type="number" pattern="[0-9]*"/>

In normal browsers, I'm typing some numbers and I'm tapping the screen, it hides iphone/ipad keyboard. 在普通的浏览器中,我正在键入一些数字而我正在点击屏幕,它隐藏了iphone / ipad键盘。

But this is not working if it is inside iframe . 但如果它在iframe内部,则无效。 we need to click done button explicitly. 我们需要明确点击完成按钮。 This issue is only for iphone/ipad 此问题仅适用于iphone / ipad

This is an iframe issue. 这是一个iframe问题。 Any fix using Javascript/Jquery would be highly appreciated. 任何使用Javascript / Jquery的修复都将受到高度赞赏。

Updated 更新

Tried 试着

 document.activeElement.blur();

and focusout when event triggered in javascript. 在javascript中触发事件时聚焦。 none of them are working.. 他们都没有工作..

   $(document).on('focusin', function(){
     $('input').css("background-color", "green");
      console.log('focusin!')
     });

  $(document).on('focusout', function(){
      console.log('focusout!')
     $('input').css("background-color", "yellow");
      $('input').blur();
     });

focusout is not calling inside iframe! focusout不是在iframe内部调用!

My question is **How to force close ipad/iphone keypad when input element is not focused using Javascript/Jquery?** 我的问题是**How to force close ipad/iphone keypad when input element is not focused using Javascript/Jquery?**

Answers will be rewarded as stated! 答案将按照规定予以奖励!

To remove the keyboard you need to lose the focus on your input. 要删除键盘,您需要失去对输入的关注。

document.activeElement.blur();

With this line you remove the focus and the keyboard disappear. 使用此行删除焦点,键盘消失。


In your case, it's possible to add an event on your body, and stop this event if you click on an input. 在您的情况下,可以在您的身体上添加事件,并在您单击输入时停止此事件。

 $(document).ready(function () { $('body').click(function () { document.activeElement.blur(); console.log("blur"); }); $('input').click(function (event) { event.stopPropagation(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"/> 


Update 更新

I found this answer to get an active element into an iframe. 我发现这个答案可以将一个活动元素放入iframe中。

/**
 * Return the active element in the main web or iframes
 * @return HTMLElement
 **/
function getActiveElement() {
  var focused = false;

  // Check if the active element is in the main web or no
  if (document.body === document.activeElement ||
    document.activeElement instanceof HTMLIFrameElement) {

    // Search in iframes
    $('iframe').each(function() {
      var element = this.contentWindow.document.activeElement;
      // If there is a active element
      if (element !== this.contentWindow.document.body) {
        focused = element;
        return false; // Stop searching
      }
    });

  } else focused = document.activeElement;

  return focused; // Return element
}

With this function you can get the active element on the document or into an iframe. 使用此功能,您可以获取文档或iframe中的活动元素。

After, you need to remove the focus on this element to hide the keyboard. 之后,您需要移除对此元素的焦点以隐藏键盘。

 getActiveElement().blur();

html target <input> and <textarea> , iphone and ipad will not hide keyboard when taping on blank area ;but android will! html目标<input><textarea> ,iphone和ipad在点击空白区域时不会隐藏键盘;但是android会! we need to hide keyboard by hand -- it means to set the input blur; 我们需要手动隐藏键盘 - 它意味着设置输入模糊;

here gose the code 这里有代码

$(function(){

    var cacheInput = null;
    var timer = null;
    if(!isApple()){
        return false;
    }
    $(document).on('focus','input',function(e){
        cacheInput = e.target;
    })
    $(document).on('focus','textarea',function(e){
        cacheInput = e.target;
    })
    $(document).on('touchend',function(e){
        if(e.target.tagName!=='INPUT'&&e.target.tagName!=='TEXTAREA'){
            if(cacheInput!==null){
                timer = setTimeout(function(){
                    cacheInput.blur();
                    clearTimeout(timer);
                },300)
            }
        }
    })
    function isApple(){
        var ua = navigator.userAgent.toUpperCase();
        var 
          ipad = ua.indexOf('IPAD')>-1,
          ipod = ua.indexOf('IPOD')>-1,
          iphone = ua.indexOf('IPHONE')>-1 ;
        return   ipad || ipod || iphone ;
    }
})

github: https://github.com/wikieswan/iphone-input-blur github: https//github.com/wikieswan/iphone-input-blur

demo: http://wikieswan.github.io/iphone-input-blur 演示: http//wikieswan.github.io/iphone-input-blur

In an ionic application I used a directive on the body that intercepts the inputs. 在一个离子应用程序中,我在身体上使用了一个拦截输入的指令。

MyApp.directive('dismissIosKeyboardOnClick', function () {
        return function (scope, element, attrs) {
          if (cordova.platformId=="ios") {
            element.on("touchstart", function(e) {
              var keyboardDoms = new Set(["INPUT","TEXTAREA","SELECT"]);
              if( keyboardDoms.has(document.activeElement.nodeName) &&
                  !keyboardDoms.has(e.target.nodeName) )
                document.activeElement.blur();
              });
            }
        };
      });

Index.html 的index.html

<body ... dismiss-ios-keyboard-on-click></body>

Hope this'll solve your issue, it simply removes the focus on active element. 希望这能解决你的问题,它只会消除对活动元素的关注。

  • Using Javascript 使用Javascript
  document.activeElement.blur(); 
  • Using jQuery 使用jQuery
  $("#Clicked_button_id").click(function() { $("#input_field_id").blur(); }); 

Try this. 试试这个。 This detects when you tab any element but the input and then blurs it. 这会检测何时标记除输入之外的任何元素然后使其模糊。

 $("html").children().not("#input_field_id").click(function(){ $("#input_field_id").blur(); }); 

I might possibly have a solution for your issue on iOS. 我可能会在iOS上为您的问题找到解决方案。 My configuration is safari on iOS 8.3/5C. 我的配置是iOS 8.3 / 5C上的safari。

From my experiments it seems to me that body element in Safari/iOS is not receptive to any click events. 根据我的实验,在我看来,Safari / iOS中的body元素不接受任何点击事件。 I am not able to explain why but it seems so. 我无法解释原因,但似乎如此。

So, what I have done is: put a wrapper div just inside body and allow it to receive the click. 所以,我所做的是:将一个包装div放在body体内并允许它接收点击。

Main.html main.html中

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>keyboard hide issue</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
    $(document).ready(function() {
        //!SOLUTION
        $('#body-wrapper').click(function(e) {
            console.log('I got clicked');
        });        
    });
</script>
<style>
/* ignore this. Its just styles. ... */
div#body-wrapper {
    height: 200px;
    width: 100%;
    background-color: red;
}
input {
    margin: 10px;
}

</style>
</head>
<body>
    <div id="body-wrapper">
        <input type="text" id="main-input1"/>
        <input type="number" id="main-input2"/>
        <input type="email" id="main-input3"/>
    </div>
    <iframe src="blur.html"></iframe>
</body>
</html>

blur.html blur.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Blur iFrame</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {   
        //!SOLUTION
        $('#wrapper').click(function(e) {
            //do nothing 
        });        
    });
</script>
<style>
/* ignore this. Its just styles. ... */
div#wrapper {
    height: 100px;
    width: 100%;
    background-color: yellow;
}
</style>
</head>
<body>
    <div id="wrapper">
        <input type="number" pattern="[0-9]*" id="main-input"/>
    </div>
    </body>
</html>

In both files I am able to hide the keyboard just fine. 在这两个文件中我都可以隐藏键盘。 Again, I don't know the underlying reason but do let me know if you aren't able to replicate the solution. 同样,我不知道潜在的原因,但如果您无法复制解决方案,请告诉我。

I have not tried it on an iPad. 我没有在iPad上试过它。 Thanks ... 谢谢 ...

Well... You can give me that reward cause I just solved this problem using a very SIMPLE solution. 嗯...你可以给我奖励因为我刚刚使用一个非常简单的解决方案解决了这个问题。

Step 1 : Check if the input is currently in focus. 步骤1 :检查输入当前是否处于焦点。 I'll explain later why we need to add a delay on changing the value of inputFocused variable. 我稍后会解释为什么我们需要在更改inputFocused变量的值时添加延迟。

var inputFocused = false;
$('input').focus(function(){
        setTimeout(function(){
            inputFocused = true;
        },100);
    });

Step 2: Add an event listener if the screen or $(window) is tapped or clicked. 第2步:如果点击或点击屏幕或$(window)则添加事件监听器。 If the window was tapped or clicked, check if the input is currently in focus. 如果点击或单击窗口,请检查输入当前是否处于焦点。 If true you must focus the window $(window).focus() , after focusing the window, the blur() function will now work! 如果为true ,则必须对焦窗口$(window).focus() ,在聚焦窗口后, blur()函数现在可以正常工作! so you can now unfocus the input element then the keyboard will now hide automatically, then set the inputFocused variable to false again. 因此您现在可以解除输入元素的聚焦,然后键盘将自动隐藏,然后再次将inputFocused变量设置为false

$(window).click(function(){
    if(inputFocused == true){
        $(window).focus();
        var input = $('input');
        input.blur();
        inputFocused = false;
    }
});`

SetTimeout explanation: The $(window).click() event will trigger if the user tap or click anywhere on the screen (eg Button click, Input click, tap or click screen, etc ). SetTimeout说明:如果用户点击或单击屏幕上的任何位置(例如按钮单击,输入单击,点击或单击屏幕等将触发$(window).click()事件。 If you tap the input, at the same time setting the inputFocused to true , the $(window).click() event triggers then check if inputFocused is true then will run the code which hides the virtual keyboard. 如果点击输入,同时将inputFocused设置为true ,则$(window).click()事件触发,然后检查inputFocused是否为true,然后将运行隐藏虚拟键盘的代码。 So it means that whenever you focus an input field the keyboard will hide and that'll be a problem. 因此,这意味着无论何时聚焦输入字段,键盘都会隐藏,这将是一个问题。

That's why we're adding a delay so that the code inside if(inputFocused == true) will not run while we're focusing the input field and it will only run if the input field is currently on focus. 这就是为什么我们添加一个延迟,以便if(inputFocused == true)中的代码在我们聚焦输入字段时不会运行,并且只有在输入字段当前处于焦点时才会运行。

TRIED AND TESTED! 经过试验和测试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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