在移動web中使用position:fixed,會踩到很多坑,在我之前的一篇文章《移動端web頁面使用position:fixed問題總結》中已經總結了很多bug,但是在后續的開發中有關fixed的未知bug越來越多,我也在盡量的尋找解決方案。
這篇文章就來先解決一個坑,fixed元素的寬度自適應。
當橫屏時,fixed元素不能自適應橫屏的寬度,bug表現如下:
這個bug主要在android自帶瀏覽器下出現,與手機型號和系統版本無關,幾乎所有android都無法幸免,在不同的手機下可能表現會有一點點差異,但都是同樣的bug。
導致bug的原因我不清楚,如有高人請指點。
下面這個解決方案在12款主流手機上測試通過(三星、小米、魅族、華為、中心等),如果還未完全解決可以回復這篇文章。
解決問題的關鍵就是:fixed元素內部必須嵌套一個position:absolute
元素,用來裝載內容,目的就是為了讓內容脫離fixed文檔流,屏蔽一些fixed的坑
別問我為什么,我也不知道為什么,但是這樣寫竟然神奇的好使了,如有高人請指點迷津。
我在下面的例子中聲明了兩種最常用的fixed元素:header和footer
position fixed header
header中我使用了float來定位左右兩邊的icon。右側icon一定不能使用position:absolute
定位,如果使用了absolute,在一些android自帶瀏覽器下橫屏時,右側icon無法自適應到右側,會出現與上面第二幅圖中差不多的bug。
<header> <div class="fixed"> <div class="wrap float"> <div class="left-icon"> <span class="glyphicon glyphicon-chevron-left"></span> </div> <h1>HEADER</h1> <div class="right-icon"> <span class="glyphicon glyphicon-calendar"></span><span class="glyphicon glyphicon-list"></span> </div> </div> </div> </header>
position fixed footer
footer中是一個flex的布局,'display:flex'容器一定不要直接聲明到fixed元素下,必須使用'position:absolute'容器包裝一層。
<footer> <div class="fixed"> <div class="wrap flex"> <a href="#"><span class="glyphicon glyphicon-picture"></span></a> <a href="#"><span class="glyphicon glyphicon-film"></span></a> <a href="#"><span class="glyphicon glyphicon-qrcode"></span></a> </div> </div> </footer>
解決方案DEMO:http://jsbin.com/omaCOSir/latest
題外話
一個placeholder自適應bug,頁面中使用<input>
標簽並且有屬性placeholder
,在頁面橫屏再轉回豎屏時,會導致頁面無法自適應,無論是android還是ios都會中招。
解決方法是,在<input>
外層容器中加overflow:hidden
,這個bug我沒有截圖,大家可以自測。
轉自:https://github.com/maxzhang/maxzhang.github.com/issues/11