如何滚动到jQuery Mobile中的页面元素?

我有一个很长的jQuery移动页面,并希望在页面加载后滚动到该页面的中间位置。

到目前为止,我已经尝试了一些事情,最成功的是:

jQuery(document).bind("mobileinit", function() { var target; // if there's an element with id 'current_user' if ($("#current_user").length > 0) { // find this element's offset position target = $("#current_user").get(0).offsetTop; // scroll the page to that position return $.mobile.silentScroll(target); } }); 

这可以工作,但是当DOM完全加载时页面位置被重置。 有谁能建议更好的方法?

谢谢

您正在寻找的活动是“pageshow”。

有点晚了,但我认为我有一个可靠的解决方案,不需要setTimeout() 。 在快速查看代码之后,似乎JQM 1.2.0在iOS上的silentScroll(0)视口的window.load上发出silentScroll(0) 。 请参阅jquery.mobile-1.2.0.js ,第9145行:

  // window load event // hide iOS browser chrome on load $window.load( $.mobile.silentScroll ); 

会发生什么,这与对silentScroll()应用调用冲突。 被称为太早,框架滚动回顶部。 被叫太晚了,用户界面闪烁。

解决方案是将一次性处理程序绑定到直接调用window.scrollTo()'silentscroll'事件( silentScroll()仅仅是异步window.scrollTo() )。 这样,我们捕获第一个JQM发出的silentScroll(0)并立即滚动到我们的位置。

例如,这里是我用于深度链接到命名元素的代码(确保在data-ajax="false"入站链接上禁用ajax加载)。 已知的锚名称是#unread#p 。 标头已修复并使用#header ID。

 $(document).bind('pageshow',function(e) { var $anchor; console.log("location.hash="+location.hash); if (location.hash == "#unread" || location.hash.substr(0,2) == "#p") { // Use anchor name as ID for the element to scroll to. $anchor = $(location.hash); } if ($anchor) { // Get y pos of anchor element. var pos = $anchor.offset().top; // Our header is fixed so offset pos by height. pos -= $('#header').outerHeight(); // Don't use silentScroll() as it interferes with the automatic // silentScroll(0) call done by JQM on page load. Instead, register // a one-shot 'silentscroll' handler that performs a plain // window.scrollTo() afterward. $(document).bind('silentscroll',function(e,data) { $(this).unbind(e); window.scrollTo(0, pos); }); } }); 

没有更多UI闪烁,它似乎可靠地工作。

我也在jQuery移动官方论坛上挖掘了很多这个问题。

目前似乎没有解决方案(至少对我而言)。

我按照上面的建议尝试了不同的事件(mobileinit,pageshow)和不同的function(silentscroll,scrolltop),但是,因此,我总是有页面滚动,直到所有图像和html完成加载,当页面再次滚动到顶部时!

部分而不是真正有效的解决方案是使用定时器,如评论sgliser的回答中所建议的那样; 不幸的是,超时很难知道何时页面将被完全加载,如果滚动发生之前 ,它将在加载结束时滚动回顶部,而如果页面完全加载发生太长时间 ,则用户已经滚动手动页面,进一步自动滚动会造成混乱。

另外,使用silentscroll或其他函数来解决特定的id或类而不是普通像素会很有用,因为使用不同的浏览器,分辨率和设备,它可能会给滚动提供不同的和不正确的定位。

希望有人能找到比这更智能,更有效的解决方案。