How to determine if a resize event was triggered by soft keyboard in mobile browser?

前端 未结 8 1695
一向
一向 2020-12-29 21:03

There\'s a lot of discussion about the soft keyboard but I haven\'t found a good solution for my problem yet.

I have a resize function like:

$(window         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 21:20

    There are a few things u need to concentrate about

    1. All soft keyboards affects only the height and not width.
    2. Focus elements tags can be either input or textarea.
    3. The height will decrease when element get focused (or) the height will increase when focused out.

    You can use these combinations when the browser gets resized

    function getWidth(){
    return $( window ).width();
    }
    
    function getHeight(){
    return $( window ).height();
    }
    
    function isFocus(){
    return $(document.activeElement).prop('tagName')=='INPUT' || $(document.activeElement).prop('tagName')=='TEXTAREA';
    }
    
    var focused = false;
    var windowWidth=getWidth(),windowHeight=getHeight();
    
    //then on resize...    
    $(window).resize(function() {
    
    var tWidth=getWidth(),tHeight=getHeight(),tfocused=isFocus();
    
    //if the saved window width is still equal to the current window width do nothing
    if (windowWidth == tWidth && ((tHeight < windowHeight && !focused && tfocused) || (tHeight > windowHeight && focused && !tfocused))){
     windowWidth=tWidth;
     windowHeight=tHeight;
     focused=tfocused;
     return;
    }
    else{
     windowWidth=tWidth;
     windowHeight=tHeight;
     focused=tfocused;
    
     //Your Code Here
    
    }
    });
    

提交回复
热议问题