我正在创建一个带有词汇表的jQuery移动应用程序。每当用户接触术语表中的某个术语时,我希望它打开术语表,用该id打开可折叠项,然后滚动到它。
// get all links within an element, assign click handler
var links = element.find(".glossaryLink");
links.each(function(index){
$(this).on("click", function(){
var regex = /\W/g;
var searchID = this.innerHTML.replace(regex, "").toLowerCase();
// open the glossary
window.location = "#glossary";
var entry = $("#" + searchID);
// This is working fine, the correct collapsible is opening
entry.collapsible( "option", "collapsed", false );
// But this always returns 0...
var pos = entry.offset().top;
// ...meaning this does nothing
$.mobile.silentScroll(pos);
}
});
代码似乎工作正常,因为我可以打开正确的可折叠(我在可折叠集内得到正确的<div>
),但是它的值pos
总是0,所以它不会滚动。
偏移量()的jQuery API表示,它不支持隐藏元素,但这个职位似乎表明,在可折叠的情况下,自动滚动是可能的。
任何帮助都非常感谢!
编辑
正如我在下面的注释中所说的,如果时间<500 As,setTimeout()技巧就无法工作。使用@Omar巧妙的解决方案分配一个侦听器然后立即启动它的工作..。
function addGlossaryClickHandlers(element){
var links = element.find(".glossaryLink");
links.each(function(index){
$(this).on("click", function(){
var regex = /\W/g;
var searchID = this.innerHTML.replace(regex, "").toLowerCase();
window.location = "#glossary";
var entry = $("#" + searchID);
// assign listener then kick it off by expanding the collapsible
entry.on("collapsibleexpand", function(){
var pos = entry.offset().top;
$.mobile.silentScroll(pos);
}).collapsible("expand");
});
});
}
上面的...but pos
再次返回0。再来一次,有人能帮忙吗?剥离了JSFiddle,尽管由于某种原因,可折叠的最后一个链接被破坏了……
发布于 2014-03-25 07:19:01
您将希望将计算offset
和silentScroll
的逻辑移到setTimeout
中。
至于你的评论:通常情况下,setTimeout(func, 0)
是标准的。但是,HTML5规范状态为4ms,因此您将看到一些使用setTimeout(func, 4)
的代码示例。
如果您对此有兴趣的话,下面将详细介绍一下发生了什么,以及为什么setTimeout解决了这个问题(这都是由于事件):
https://stackoverflow.com/a/4575011/1253479
谢谢!
https://stackoverflow.com/questions/22622860
复制相似问题