码迷,mamicode.com
首页 > 其他好文 > 详细

position sticky的兼容

时间:2017-07-27 21:28:20      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:ntop   null   nav   osi   兼容   动态添加   blog   sticky   put   

  position的sticky这个属性一般用于导航条,因为他在屏幕范围(viewport)时该元素的位置并不受到定位影响(设置是top、left等属性无效),当该元素的位置将要移出偏移范围时,定位又会变成fixed,根据设置的left、top等属性成固定位置的效果。基本就是自适应的导航条

  但是其兼容性在ios上很流畅,但是再安卓上,安卓4.4.4以下全军覆没,莫名其妙在安卓7上也跪了。可能你会想,既然兼容那么差,为什么还要用。在微信浏览器上,滚动并不是即时的,它需要等滚动完,scroll事件才触发,这样通过js计算距离屏幕顶端距离,然后fixed和relative定位切换,并不流畅,会卡顿。而sticky却非常流畅,不能因为一部分用户的兼容不了,放弃使用这个属性。

  那么只能通过判断当前设备是否支持sticky这个属性,如果不支持则替换成fixed和relative定位组合;

  以下是demo代码

  

  let elem = window.document.documentElement;
  let w = elem.clientWidth;
  let h2 = (w/16*9);//使用sticky定位的顶端是一个16比9的div
  function isSupportSticky() {//判断是否支持sticky
    var prefixTestList = [‘‘, ‘-webkit-‘];
    var stickyText = ‘‘;
    for (var i = 0; i < prefixTestList.length; i++ ) {
      stickyText += ‘position:‘ + prefixTestList[i] + ‘sticky;‘;
    }
    // 创建一个dom来检查
    var div = document.createElement(‘div‘);
    div.style.cssText = stickyText;
    document.body.appendChild(div);
    var isSupport = /sticky/i.test(window.getComputedStyle(div).position);
    document.body.removeChild(div);
    div = null;
    return isSupport;
  }
  let fixBottomBar = function(){
    var  topbarTop = h2;
    window.onscroll = function(e){
      let winTop = document.body.scrollTop;
      if(winTop > topbarTop){
          _this.navClass[‘nav-fixed‘] = true;  //vue动态添加class写法
//            topbar.setAttribute(‘class‘,‘nav nav-fixed‘);  //原生js写法
      }else{
        _this.navClass[‘nav-fixed‘] = false;
//            topbar.setAttribute(‘class‘,‘nav‘);
      }
    }

  }
  !isSupportSticky() && fixBottomBar();

 

position sticky的兼容

标签:ntop   null   nav   osi   兼容   动态添加   blog   sticky   put   

原文地址:http://www.cnblogs.com/cjh1111/p/7246977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!