Get viewport height when soft keyboard is on

后端 未结 7 1807
梦如初夏
梦如初夏 2021-01-31 08:45

I\'ve been trying to make this work for days now, with no luck, so I thought I\'d share info and maybe someone comes up with a solution.

I want to get the exact viewport

7条回答
  •  后悔当初
    2021-01-31 09:32

    I came up with this hack:

    var storedWidth = 0;
    var storedHheight = 0;
    
    function onResize() {
    
      var windowWidth = $(window).width();
      var windowHeight = $(window).height();
      var screenWidth = screen.width || windowWidth;
      var screenHeight = screen.height || windowHeight;
      var width, height;
    
      if(screenWidth < screenHeight) {
        if(windowWidth > storedWidth) storedWidth = windowWidth;
        if(windowHeight > storedHeight) storedHeight = windowHeight;
        width = storedWidth;
        height = storedHeight;
      }else {
        width = windowWidth;
        height = windowHeight;
      }
    
      //use width and height from here
    
    }
    

    Now this would fail in two cases:

    • screen.width/screen.height not being supported; it would fallback to the erroneous jquery dimensions. In my case, the soft keyboard made the height smaller than the width while in portrait mode, so the jQuery dimensions resulted in a false landscape mode and thus showing the 'rotate your device' message.

    • the page is opened with the soft keyboard opened, which I think is moot. Also after hiding it, the largest height is stored so things will be fixed after that.

    Note:

    • window.innerWidth/window.innerHeight could be used to ditch the jQuery dependency

    • above code is to fix the keyboard issue in portrait mode, but same solution could be used for landscape mode

提交回复
热议问题