let len = document.getElementById('flexbox').getBoundingClientRect().top;//获取元素到浏览器视窗顶部的距离
//$(document).scrollTop()为滚动条的高度
for (let i = $(document).scrollTop(); i < len + $(document).scrollTop(); i++) {
setTimeout(function () {
window.scrollTo(0, i);
}, 0)
}
用循环的目的主要是使得元素置顶的时候不突兀,这个过程可以通过改变i++来实现,同时需要注意一点,如果for语句用的是var i 而不是let i,定时器则需要用立即执行函数包裹来保证i能立马生效。