經(jīng)過百度與stackoverflow
4年前還有很多quirks模式的時(shí)候 原因是這樣的
Firefox & IE 支持對(duì)html的scroll 部分webkit 支持 body 的scroll ( 360 極速模式實(shí)驗(yàn)成功 )
而在老的瀏覽器中, 打開一個(gè)空白頁面匠童,觀察瀏覽器右側(cè),會(huì)發(fā)現(xiàn)IE瀏覽器會(huì)有一段滾動(dòng)條沛膳,而Firefox瀏覽器下沒有
直至body scrollTop 被廢棄, 詳見w3c標(biāo)準(zhǔn)
scrollTop ( 距頂部滾動(dòng)距離 ) 是有滾動(dòng)條的html ( 或其他元素 ) 才有的
body is not potentially scrollable 不可能滾動(dòng)
當(dāng)然, 可以動(dòng)手給body 加個(gè) overflow: scroll
, 或者給html 加個(gè) hidden
所以 回到頂部中 animate 對(duì) body 進(jìn)行 scrollTop屬性, 自然不行
在jquery的github和官網(wǎng)上, 也有類似的issue
$( "html, body" ) 的兼容性寫法還是很好的
唯一的缺點(diǎn)是會(huì)造成兩次回調(diào)
$( "html, body" ).animate({scrollTop:0}, 500, function() {
alert("Finished animating"); // 彈出兩次
});
但是可以用promise來解決這個(gè)問題
$( "html, body" ).animate({ scrollTop: 0 }, 100)
.promise().then(function() {
console.log("runs once!")
});
當(dāng)然如果不要?jiǎng)赢嬓Ч透唵瘟? 原生或者jquery 都可以
$( document ).scrollTop( 500 );
window.scrollTo(0,0)
document.body.scrollTop = document.documentElement.scrollTop = 0;
document.body.scrollIntoView();
最后配個(gè)實(shí)驗(yàn)圖