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

bod*_*ous 4 javascript jquery 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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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

谢谢

fbo*_*net 10

有点晚了,但我认为我有一个可靠的解决方案,没有必要setTimeout().在快速查看代码之后,似乎JQM 1.2.0 在iOS silentScroll(0)window.load为chromeless视口发布了一个on .见jquery.mobile-1.2.0.js第9145行:

    // window load event
    // hide iOS browser chrome on load
    $window.load( $.mobile.silentScroll );
Run Code Online (Sandbox Code Playgroud)

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

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

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

$(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);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

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