javascript 键盘弹出时向上滚动文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18450659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:58:54  来源:igfitidea点击:

Scroll textfield up when keyboard popsup

javascriptandroidandroid-layoutandroid-softkeyboard

提问by user533844

I am using html5/javascript/jQuery/css for mobile app development. I have multiple textareas in the app. When I click on that to input, keyboard popup (android tab). But the textarea stays where it's on that page. How can I scroll page when keyboard pops up.

我正在使用 html5/javascript/jQuery/css 进行移动应用程序开发。我在应用程序中有多个文本区域。当我点击它进行输入时,键盘弹出窗口(android 选项卡)。但是 textarea 保留在该页面上的位置。键盘弹出时如何滚动页面。

回答by MikeM

with jQuery, get the textarea's offset().topvalue then set document scroll position using scrollTop()

使用 jQuery,获取 textarea 的offset().top值,然后使用设置文档滚动位置scrollTop()

var $htmlOrBody = $('html, body'), // scrollTop works on <body> for some browsers, <html> for others
    scrollTopPadding = 8;

$('textarea').focus(function() {
    // get textarea's offset top position
    var textareaTop = $(this).offset().top;
    // scroll to the textarea
    $htmlOrBody.scrollTop(textareaTop - scrollTopPadding);
});

jsfiddle example

jsfiddle 示例

回答by Ludo

To complete the answer, if you want to animate the scroll replace:

要完成答案,如果要为滚动替换设置动画:

$htmlOrBody.scrollTop(textareaTop - scrollTopPadding);

by

经过

var timing = 250;
$htmlOrBody.animate({ scrollTop: textareaTop - scrollTopPadding }, timing);

回答by jafar690

just detect browser window size change, when keyboard pops up, the browser window size will change

只检测浏览器窗口大小的变化,当键盘弹出时,浏览器窗口大小会发生变化

$(window).resize(function() {
    var $htmlOrBody = $('html, body'), // scrollTop works on <body> for some browsers, <html> for others
    scrollTopPadding = 8;
    // get input tag's offset top position
    var textareaTop = $(this).offset().top;
    // scroll to the textarea
    $htmlOrBody.scrollTop(textareaTop - scrollTopPadding);

    // OR  To add animation for smooth scrolling, use this. 
    //$htmlOrBody.animate({ scrollTop: textareaTop - scrollTopPadding }, 200);
});