当 position:sticky 遇到 bootstrap 浮动布局时候的踩坑记录
當(dāng)?shù)谝淮谓佑|到 position:sticky 這個屬性,我就意識到之前的不少 js 場景可以用這個 css 屬性去改寫。譬如 網(wǎng)站 右側(cè)的不少廣告,滾動上去后需要 fixed,完全就是 sticky 的應(yīng)用啊。
今天要說的是 文章詳情頁 右側(cè)的目錄欄,當(dāng)頁面下滑的時候,它也會固定到頁面頂部,之前是用 js 去監(jiān)聽 scroll 事件,然后根據(jù)位置進(jìn)行判斷,toggle fixed 的方案,出于一些原因,決定對它用 sticky 去重寫。
幾下就寫完了,去掉滾動事件監(jiān)聽,然后將菜單元素 .post-nav 加上 position:sticky; top:0 樣式,但是,不起效!
wtf! 百思不得其解,我開始搜索原因。在 so 搜到了 這個,說到可能是元素的父級元素有對 overflow 屬性進(jìn)行處理,比如加了什么 overflow:hidden 啥的,但是看了下,并沒有這種情況。
然后我猜想會不會是 bootstrap 布局的問題(事實上確實有關(guān)系),寫下 demo:
<!DOCTYPE html> <html> <head><title></title><link href="//cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"><style>body {font-size: 50px; font-weight: 900;}.main {height: 2000px; background: #eee}.menu {height: 200px; background: yellow}.ad {height: 200px; background: red; position: sticky; top: 0px;}.guess {height: 200px; background: blue;}</style> </head> <body> <div class="container"><div class="row"><div class="col-md-8 main">content</div><div class="col-md-4"><div class="menu">menu</div><div class="ad">ad</div><div class="guess">others</div></div></div> </div> </body> </html>但是沒問題,突然想到網(wǎng)站用的 bootstrap 版本是 3.x,然后改成 3.3.7 的版本,這時候問題就出來了。
這時候問題就比較好定位了,4.x 用的是 flex 布局,而 3.x 還是 float 浮動布局,問題應(yīng)該是出在這里了。
最終代碼(參考 這個 issue):
<!DOCTYPE html> <html> <head><title></title><link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"><style>body {font-size: 50px; font-weight: 900;}.main {height: 2000px; background: #eee}.side {height: 2000px;}.menu {height: 200px; background: yellow}.ad {height: 200px; background: red; position: sticky; top: 0px;}.guess {height: 200px; background: blue;}</style> </head> <body> <div class="container"><div class="row"><div class="col-md-8 main">content</div><div class="col-md-4 side"><div class="menu">menu</div><div class="ad">ad</div><div class="guess">others</div></div></div> </div> </body> </html>對應(yīng)到開始的問題上,因為 menu 是屬于 .col-md-3 元素的,所以右邊的 .col-md-3 需要和左邊的 .col-md-9 保持高度一致即可,加上這行代碼:
$('.side').height($('.main').height())因為左邊的內(nèi)容區(qū)域有圖片的延遲加載,所以這行代碼需要持續(xù)執(zhí)行:
$(window).scroll(function() { $('.side').height($('.main').height())// other code // ...})總結(jié)
以上是生活随笔為你收集整理的当 position:sticky 遇到 bootstrap 浮动布局时候的踩坑记录的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿里云开启多媒体搜索新时代,发布全域精准
- 下一篇: hashMap怎么解决hash冲突的