window.scrollTo无法在phonegap中工作 – 替代解决方案或解决方法?

我已经编写了一个相当基本的js函数,它以编程方式自动对齐iPhone键盘,完美地聚集在每个输入区域的下方如果你喜欢它 ,可以随意使用它 !)。 对齐主要由window.scroll处理 – 一种适用于任何浏览器视图的标准方法,除了UIWebView因此phonegap / cordova(2.1)所以我需要一个解决方法

我的工作代码:

function setKeyboardPos(tarId) { //programmatically: set scroll pos so keyboard aligns perfectly underneath textfield var elVerticalDistance = $("#"+tarId).offset()["top"]; //ie 287 var keyboardHeight = 158; var heightOfView = document.height; // ie 444 var inputHeight = $("#"+tarId).outerHeight(); var viewPortSpace = heightOfView-keyboardHeight; //ie 180 var verticalNewSroll = (elVerticalDistance+inputHeight)-viewPortSpace; if(verticalNewSroll<0) { verticalNewSroll = 0; } //// //OK, all done lets go ahead with some actions $("#footer").hide(); //hide footer so that the keyboard doesn't push it on top of textfield $("#containingDiv").css("bottom","0px"); //remove bottom space for footer window.scrollTo(0,verticalNewSroll); //scroll! where the problem starts } 

除了UIWebView以外的所有工作。 正如我上面提到的,除了window.scrollTo之外,一切都有效(为了清晰起见,已经进行了一些小的改动)。 那么有人知道替代解决方案甚至是一个好的解决方法吗?

类似的问题

window.scrollTo在IOS的phonegap中不起作用

PhoneGap / Cordova s​​crollTo Ignored

如何在Phonegap中添加垂直滚动

以上是三个类似的问题,有点指向一个正确的方向。 其中一位回答者提到使用css来实现这一目标 。 任何人都能想出一个更具体的例子吗? 另一个人建议锚点,但这不是一个非常漂亮的解决方案,并且与我的其余代码不太一致。

在做了一些研究之后,我意识到window.scrollTo()确实在带有phonegap 2.1的iOS6中工作,还有其他一些失败的东西; 出于某种原因,document.height在UIwebView中没有产生相同比例的属性,所以我不得不写一个小的解决方法。 我将在下面发布解决方案和整个代码以供将来参考。

 function setKeyboardPos(tarId) { //programmatically: set scroll pos so keyboard aligns perfectly underneath textfield var elVerticalDistance = $("#"+tarId).offset()["top"]; var keyboardHeight = 157; if(isNativeApp()) { keyboardHeight = 261; } //I choose to change the keyboard height for the sake of simplicity. Obviously, this value does not correnspond to the actual height of the keyboard but it does the trick var keyboardTextfieldPadding = 2; var heightOfView = document.height; var inputHeight = $("#"+tarId).outerHeight(); var viewPortSpace = heightOfView-keyboardHeight-keyboardTextfieldPadding; //180 var verticalNewSroll = (elVerticalDistance+inputHeight)-viewPortSpace; if(verticalNewSroll<0) { verticalNewSroll = 0; } //// //OK, all done lets go ahead with some actions $("#footer").hide(); //hide footer so that the keyboard doesn't push it on top of textfield $("#containingDiv").css("bottom","0px"); //remove bottom space for footer window.scrollTo(0,verticalNewSroll); // perform scroll! } function isNativeApp() { var app = (document.URL.indexOf('http://') === -1) && (document.URL.indexOf('https://') === -1); if (app) { return true; // PhoneGap native application } else { return false; // Web app / safari } } 

你可以尝试使用animate和scrollTop属性来滚动它看起来像这样:

 $("html, body").animate({ scrollTop: "The value to scroll to" }); 

希望这可以帮助。

你只需要使用它:

 $(window).scrollTop(0);