position:sticky是一个新的css3属性,它的表现类似position:relative和position:fixed的合体。

 在可视区域内,表现是 relative属性

超过区域外,固定在屏幕上,表现是 fixed属性

一般方法是用js控制 position为 relative 和 fixed切换,但手机上滑动会有些滞后,卡顿,而 sticky属性能平滑过渡。

判断sticky代码:

function supportSticky(str){
            var t,
                n = str,
                e = document.createElement("i");
            e.style.position = n;
            t = e.style.position;
            e = null;
            return t === n;
        }

对不支持sticky的处理:

$(window).bind('scroll', function () {
            var isSticky = supportSticky('sticky') || supportSticky('-webkit-sticky');

            if(!isSticky){
                if ($(this).scrollTop() < top_nav) {
                    $el.removeClass('fixed');
                } else {
                    $el.addClass('fixed');
                }
            }
        });

css写法:

.scrollMenu{
    position: -webkit-sticky;
    position: sticky;
    top: 0;
    width: 100%;
    height: 36px;
    z-index: 1000;
}

注意:如果body的css 设置overflow: hidden; 

        则 sticky失效。

 

相关文章:

  • 2022-01-04
  • 2022-01-18
  • 2021-12-30
  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-23
  • 2021-09-24
  • 2021-06-15
  • 2022-12-23
  • 2021-06-25
相关资源
相似解决方案