Detect virtual keyboard vs. hardware keyboard

前端 未结 6 2100
心在旅途
心在旅途 2020-12-05 06:36

I have been thinking about this a while now, and I can\'t figure a way to deal with it. Is there any way to detect if the user uses a virtual (software) keyboard or a tradit

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 07:11

    The most bullet prof solution that works across Chrome/Safari etc.. and on both Android and iOS as of 20-nov-2017 will be to detect a change in the height of a div that has a vh height units (viewport height)

    Then on any blur/focus change of an input/textarea check if that div now has a height of 30% less (in pixels) than it used to have before that blur/focus event.

    CSS:

    #height-div{height: 10vh;}
    

    jQuery:

    $(document).ready(function() {
        var initialHeight = $("#height-div").height();//gives current height in pixels! We save it for later comparisons 
    }
    

    Now here is the magic:

    $("input, textarea").focus(function(){
            setTimeout(function(){
                if((initialHeight*0.7) > $("#height-div").height()){//if the current viewport height is smaller than 70% of the original size, it means that the keyboard is up
                    //ENTER YOUR LOGIC HERE
                }else if((initialHeight*0.7) < parent.$submit.height()){//if the current viewport height is larger than 70% of the original size, it means that the keyboard is down
                //ENTER YOUR LOGIC HERE
                }
            },500);
    });
    
    $("input, textarea").blur(function(){
            setTimeout(function(){
                if((initialHeight*0.7) > $("#height-div").height()){//if the current viewport height is smaller than 70% of the original size, it means that the keyboard is up
                    //ENTER YOUR LOGIC HERE
                }else if((initialHeight*0.7) < parent.$submit.height()){//if the current viewport height is larger than 70% of the original size, it means that the keyboard is down
                //ENTER YOUR LOGIC HERE
                }
            },500);
    });
    

提交回复
热议问题