javaScript让前端飞

优化之黏性吸顶(sticky)

2019-04-28  本文已影响50人  反者道之动001

如何正确在项目使用sticky优化吸顶用户体验

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,对不起,不会生效。

(其实这本身就不坑。好比如你使用滚动插件的时候,你需要设置高度一样,因为这样好确定位置,如果要冒泡的话,消费比较多的资源)

但是呢,兼容性不乐观,于是我们需要进行降级方案。

怎么降级,用什么呢?

当然是用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;'
    }
    // 创建一个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是圆角。然后顶部的背景颜色和背景不一致。看图

父元素overflow的部分背景色和圆角的背景是用同一个background-color的,这时候要不一样怎么办?

背景是不能改了,给子元素台南佳div也不行,因为这样sticky就失效了。
于是本人添加一个定位元素在后面。

隔壁女神说:(擦,天才啊)


但是好像一滚动,发现不对劲了。

给跑前面了

这时候才明白,原来女神这个手势的意思是,请开始你的表演。

(愚笨的我,立刻在内容层(tab下面的内容的box元素)添加如下代码)

    z-index: 2;
    position: relative;

看起里好像没问题。

不过,仔细看。

滑动一定位置的时候会出现这个问题。
因为absolute定位的是固定的,而tab是动态的。

所以,修改上面的布局,或者, 写两个圆角直接在tab内部定位到左上角或者右上角。

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


--END--

上一篇下一篇

猜你喜欢

热点阅读