JQuery mobile pagecontainertransition事件无法按预期工作

时间:2015-09-18 12:08:09

标签: javascript jquery jquery-mobile javascript-events

我有一个jquery移动网站,在进入我的wnat后跳转到页面上的某个部分:

$(document).on('pagecontainertransition', function(event, ui){
  $(window).scrollTop( $("#mysection").offset().top);   
  console.log("pause");
});

如果我加载页面并从javascript控制台运行scrolltop行,它可以正常工作。

如果我在console.log("pause");行放置一个javascript断点,我会看到屏幕上的页面正是我想要的。该页面被跳转到mysection。但是,如果我释放断点,它会跳回到页面顶部。

从文档和谷歌搜索我明白

  

pagecontainertransition

是最后一个Jquery移动事件。

我缺少什么?

由于

3 个答案:

答案 0 :(得分:1)

试试这个

$(document).on('pagecontainertransition', function(event, ui){  
   $('html, body').animate({
        scrollTop: $("#mysection").offset().top
    }, 1000);
  console.log("pause");
});

答案 1 :(得分:1)

jQuery Mobile提供了一种可以使用的滚动方法:

https://api.jquerymobile.com/jQuery.mobile.silentScroll/

此外,当加载页面时,jQM会自动滚动到顶部,所以可能你有时间问题,需要引入一个小延迟:

$(document).on('pagecontainertransition', function(event, ui){
    if (ui.toPage.prop("id") == "page2"){
        setTimeout(function(){
            $.mobile.silentScroll( $("#mysection").offset().top); 
        }, 100);
    }
});
  

<强> DEMO

答案 2 :(得分:0)

感谢Akki619和ezanker让我走上正轨:

我的问题是由加载后jquery移动滚动到页面顶部引起的。我不想使用超时(在旧的移动设备上可能太短或在台式计算机上太长)。我在谷歌上搜索https://forum.jquery.com/topic/jquery-mobile-scroll-to-top-of-page-on-page-load我有办法在JQM中覆盖这种行为,满足了我的需求。在那里,我将以下代码添加到我的javascript:

(function($)
{
  $( document ).on( "mobileinit", function()
  {
    var silentScroll = $.mobile.silentScroll;
    $.mobile.silentScroll = function( ypos )
    {
        if ( $.type( ypos ) !== "number" )
        {
            // FIX : prevent auto scroll to top after page load
            return;
        }
        else
        {
            silentScroll.apply(this, arguments);
        }
    };
});
}
(jQuery));
相关问题