我有一个充满预先输入搜索结果的 div。当 typeahead 绑定(bind)到的输入失去焦点时,我希望将具有 typeahead 结果的 div 滚动到最顶部的位置。
我正在使用 typeahead.js ,所以我目前有:
$('input[name="customer"]').on('typeahead:closed', function(){
$('div.tt-dataset-customers').scrollTop(0);
});
然而,div 永远不会滚动。认为这是由于 div 被隐藏,我也试过:
$('input[name="customer"]').on('typeahead:open', function(){
$('div.tt-dataset-customers').scrollTop(0);
});
这也不起作用。
有没有办法在未显示的 div 上设置滚动位置?
显示正在发生的事情的 fiddle :http://jsfiddle.net/tTdF4/
最佳答案
编辑 v3
所以我在上面添加了一个 console.log
,但它从未触发。
$('input[name="customer"]').on('typeahead:closed', function(){
console.log('test');
});
因此,我没有将 typeahead()
从 on()
中分离出来,而是使用了 jQuery 链,现在它触发了 typeahead:closed
.不要问我为什么没有触发,我还没弄明白:(。
无论如何,当您键入 a
、向下滚动、单击外部然后单击返回输入时,这将起作用(在 chrome v29 上测试),列表将备份。
$('input[name="customers"]').typeahead({
local: ['a','ab','ac','ad','ae','af',
'ag','ah','ai','aj','ak','al',
'am','an','ao','ap','aq','ar',
'as','at','au','av','aw','ax',
'ay','az'
],
limit: 20,
name: 'customers',
rateLimitWait: 100,
ttl: 300
}).on('typeahead:closed keypress', function(){
console.log('test');
$('div.tt-dataset-customers').animate({
scrollTop: 0
}, 900);
});
p.s.: 至少在 fiddle 上,jquery 2.X 和 typeahead 在 IE9 上的两个 scritps 上都给出了错误(见控制台),如果你使用 1.9 (edge)
那么它会工作。
V3:添加了 keypress
到监听的事件中,因此它会在每次有人键入内容时尝试向上滚动(包括键入 a
、退格键和键入 b
例如)。
关于javascript - 不显示时滚动到div的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18218086/