我有一个很长的 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 完全加载时页面位置会被重置。谁能提出更好的方法?
Thanks
有点晚了,但我想我有一个可靠的解决方案,不需要setTimeout()
。快速查看代码后,似乎 JQM 1.2.0 发出了silentScroll(0)
on window.load
适用于 iOS 上的 chromeless 视口。看jquery.mobile-1.2.0.js
,第 9145 行:
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
发生的情况是,这与应用调用冲突silentScroll()
。调用得太早,框架会滚动回顶部。调用得太晚,UI 闪烁。
解决方案是将一次性处理程序绑定到'silentscroll'
调用的事件window.scrollTo()
直接地 (silentScroll()
只不过是异步的window.scrollTo()
反正)。这样,我们就捕获了 JQM 发布的第一个silentScroll(0)
并立即滚动到我们的位置。
例如,下面是我用于深层链接到命名元素的代码(请确保禁用入站链接上的 ajax 加载)data-ajax="false"
)。已知的锚点名称是#unread
and #p<ID>
。标头是固定的并使用#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 不再闪烁,而且看起来工作可靠。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)