安卓软触屏键盘遮挡输入框

7

我有一个简单CSS的PHP Web应用程序。当我在Android平板电脑上运行该应用程序并尝试登录时,软键盘会弹出并隐藏我的文本输入字段。我尝试在Stack Overflow上搜索类似的问题,但所有问题都与ASP.NET相关,没有具体提到其他语言。

我已经尝试了以下解决方案,但没有起作用:

// 在document.ready函数中添加此代码

if(navigator.userAgent.indexOf('Android') > -1){           
     $('html').css({ "overflow": "auto !important" });
     $('body').css({ "height": "auto !important" });
     $('body').css({ "overflow": "auto !important" });
     $('.scrollable').css({ "position": "inherit !important" });
     $('body').on('focusin', 'input, textarea', function(event) {
          //alert("test");
          var scroll = $(this).offset();
          window.scrollTo(0, scroll);               
     });
}

或者
//在CSS文件中添加

html { 
   overflow: auto; 
} 
body { 
   height:auto; 
   overflow: auto; 
} 
.scrollable { 
   position:inherit; 
}

请帮忙。 谢谢。
2个回答

4
我为您准备了一个 JSFiddle,也许您可以使用它:https://jsfiddle.net/fe82uhrp/1/ JS:
/***** using jQuery *****/

$('input').focus( function() {

    var $input = $(this);
    $input.css('background', 'yellow');

    var scroll = $input.offset();
    $input.closest('#viewport').animate({
      scrollTop: $input.offset().top
    }, 'slow');
});


/***** using plain JS *****/

var viewport = document.getElementById('viewport');
var allInputs = document.getElementsByTagName('input');
for( var i=0; i<allInputs.length; i++) {

    var item = allInputs[i];
    console.log('set focus event handler on', item)
    item.onfocus = function() {
        this.style.background = "yellow";
        item.scrollIntoView();
    }
};

我不会使用滚动整个窗口,而是使用一个页面包装容器(例如在我的示例中#viewport)。


谢谢,我已经用那种方法完成了,现在完美运行 :) - ph1409

0

这里是 React 代码,你可以将其放在根组件中。 例如:src/App/index.js

componentDidMount() {
  window.addEventListener('resize', this.handleKeyboardAvoiding);
}
componentWillUnmount() {
  window.removeEventListener('resize', this.handleKeyboardAvoiding);
}
handleKeyboardAvoiding = () => {
  const focusedElement = document.activeElement;
  if (focusedElement.tagName.toLowerCase() === 'input') {
    focusedElement.scrollIntoView({ behavior: 'smooth' });
  }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接