我有一个CSS动画的 Accordion ,可扩展单击的li。这是使用li:target完成的。
现在,我想滚动到被单击的id,但是由于css转换,它最终定位在激活转换之前li所在的位置。
到目前为止,这是我的javascript代码段:
$(document).on('click', '#accordion li', function (e){
e.preventDefault();
// Call the scroll function
goToByScroll($(this).attr("id"));
$('#accordion li').height('');
$(this).height($('section', $(this)).outerHeight() + $('a', $(this)).outerHeight());
});
// This is a functions that scrolls to #ID
function goToByScroll(id){
// Scroll
// Wait until CSS transition is done
$("#"+id).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
$('html,body').animate({
scrollTop: $("#"+id).offset().top},
'fast');
$("#"+id).unbind();
});
}
Edit2:在Piotr的建议之后,取消绑定(bind)事件修复了我的 buggy 行为:)
最佳答案
你可以试试:
$("#"+id).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(event){
$('html,body').animate({
scrollTop: $("#"+id).offset().top},
'fast'
);
$(this).unbind(event);
});
编辑:添加了取消绑定(bind)的说明。