優(yōu)化之黏性吸頂(sticky)

如何正確在項目使用sticky優(yōu)化吸頂用戶體驗

MDN是這樣講sticky的

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.
This value always creates a new stacking context. Note that a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn't the nearest actually scrolling ancestor. This effectively inhibits any "sticky" behavior (see the Github issue on W3C CSSWG).

具體看文檔 https://developer.mozilla.org/en-US/docs/Web/CSS/position

我們說說注意事項

比較坑的就是對父元素的要求,也就是 父元素一定需要滾動(父元素哦),不然你看不到效果。比如你在前面包一層div,對不起,不會生效。

(其實這本身就不坑。好比如你使用滾動插件的時候,你需要設(shè)置高度一樣,因為這樣好確定位置,如果要冒泡的話,消費比較多的資源)

但是呢,兼容性不樂觀,于是我們需要進(jìn)行降級方案。

怎么降級,用什么呢?

當(dāng)然是用JS了。先判斷下是否支持

/**
* 判斷是否css3中的Sticky屬性
* @returns {boolean}
*/
export const isSupportSticky = function() {
    var prefixTestList = ['', '-webkit-', '-ms-', '-moz-', '-o-']
    var stickyText = ''
    for (var i = 0; i < prefixTestList.length; i++) {
        stickyText += 'position:' + prefixTestList[i] + 'sticky;'
    }
    // 創(chuàng)建一個dom來檢查
    var div = document.createElement('div')
    var body = document.body
    div.style.cssText = 'display:none;' + stickyText
    body.appendChild(div)
    var isSupport = /sticky/i.test(window.getComputedStyle(div).position)
    body.removeChild(div)
    div = null
    return isSupport
}

不支持就JS控制就好了。如 isSupportSticky() || ceiling(父元素DOM哦)

順便附上代碼

function ceiling(obj) {
    var ot = obj.offsetTop;
    var box = obj.parentNode
    box.onscroll = function () {
        var st = box.scrollTop || box.scrollTop
        obj.style.position = st >= ot ? "fixed" : ""
    }
}

好了完美


這時候,如果UI是圓角。然后頂部的背景顏色和背景不一致??磮D

父元素overflow的部分背景色和圓角的背景是用同一個background-color的,這時候要不一樣怎么辦?

背景是不能改了,給子元素臺南佳div也不行,因為這樣sticky就失效了。
于是本人添加一個定位元素在后面。

隔壁女神說:(擦,天才?。?/p>

但是好像一滾動,發(fā)現(xiàn)不對勁了。

給跑前面了

這時候才明白,原來女神這個手勢的意思是,請開始你的表演。

(愚笨的我,立刻在內(nèi)容層(tab下面的內(nèi)容的box元素)添加如下代碼)

    z-index: 2;
    position: relative;

看起里好像沒問題。

不過,仔細(xì)看。

滑動一定位置的時候會出現(xiàn)這個問題。
因為absolute定位的是固定的,而tab是動態(tài)的。

所以,修改上面的布局,或者, 寫兩個圓角直接在tab內(nèi)部定位到左上角或者右上角。

--ok,好像我看到了女神的鼓掌--


--END--

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容