侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

移动端吸顶fixbar的解决方案详解

前端  /  管理员 发布于 4年前   333

需求背景

经常会有这样的需求,当页面滚动到某一个位置时,需要某个页面元素固定在屏幕顶部,并且有时需要连续滚动吸顶。在PC端主要的实现是通过 CSS 的 position: fixed 属性,但是在移动端,尤其是在安卓端,存在诸多的兼容性问题。

问题

position:fixed给移动端带来的问题:

  • IOS8在页面滚动时,吸顶不连续;页面滑动时,不见吸顶,页面滚动停止后,吸顶缓慢出现
  • 滚动到顶部之后,会出现两个一样的吸顶, 过一会才恢复正常。
  • footer底部输入框 focus 状态,footer 底部输入框被居中,而不是吸附在软键盘上部。
  • iPhone 4s&5 / iOS 6&7 / Safari 下,页面底部footer输入框失去焦点时,header定位出错。当页面有滚动动作时,header定位恢复正常。
  • iPhone 4 / iOS 5 / Safari下,当页面发生跳转,再退回时,fixed区域消失,当内容获得焦点时,fixed区域才显示。
  • 安卓低版本/自带浏览器,不支持fixed属性,iOS4 也是不支持 fixed 的。
  • 三星i9100(S2) / 自带浏览器,在滚屏过程中,fixed定位异常,touchend之后恢复正常。
  • 部分低版本Android对支持不好,video poster属性设置的封面图会遮挡fixed元素。
  • QQ、UC浏览器滚动页面时footer定位错误,会往上偏移,是由于地址栏收起的缘故。
  • *remind:不要在 fixed 元素中使用 input / textarea 元素。

解决方案

分别处理各个问题:

IOS

在IOS端,使用 position: sticky 这个属性,使用类似于 position: relative 和 position: absolute 的结合体。在目标区域在屏幕中可见时,它的行为就像position:relative; 而当页面滚动超出目标区域时,它的表现就像position:fixed,它会固定在目标位置。

使用时,需要加上私有前缀

position: -webkit-sticky;position: -moz-sticky;position: -ms-sticky;position: sticky;

对于 position:sticky 的使用,需要注意很多的细节,sticky满足以下条件才能生效:

1、具有sticky属性的元素,其父级高度必须大于sticky元素的高度。

2、sticky元素的底部,不能和父级底部重叠。(这条不好表述,文后详细说明)

3、sticky元素的父级不能含有overflow:hidden 和 overflow:auto 属性

4、必须具有top,或 bottom 属性。

同时要注意,sticky元素仅在他父级容器内有效,超出容器范围则不再生效了。

安卓

滚动距离超过某位置时,js动态设置样式;为了防止惯性滚动引起的fix不及时的情况,在 touchstart、 touchmove 、 touchend 事件都进行监听。

// 注意处理遮罩层的位置  var scrollHandler = function () {    if (topLength < me.getScrollTop()) {      target.css('position', 'fixed');      me.replaceEle.show();    }    else {      target.css('position', 'relative');      me.replaceEle.hide();    }  };  // 安卓情况下,防止惯性滚动引起的fix不及时的情况  if (/(Android)/i.test(navigator.userAgent)) {    $(window).on('scroll', scrollHandler);    $(document.body).on('touchstart', scrollHandler);    $(document.body).on('touchmove', scrollHandler);    $(document.body).on('touchend', function () {      scrollHandler();      setTimeout(scrollHandler, 1000);    });  }

不支持sticky

如果浏览器不支持position:sticky,那么就使用js动态的在节点在fixed定位于static定位中切换,但是需要对切换过程做一些优化。

1、使用函数节流防抖减少dom操作频繁粗发,但是保证在规定时间内必须执行一次。

2、使用window.requestAnimationFrame 方法在下一帧前触发浏览器的强制同步布局,是对dom的操作能及时渲染到页面上。

3、减少对dom的读写操作,或者把dom操作把读、写操作分开,可以减少渲染次数。

原文代码

(function() {  function Sticky(){    this.init.apply(this, arguments);  }  /**   * 滚动fixed组件初始化   * @param {object}     setting        allocate传进来的参数   * @param {object}     setting.stickyNode   需要设置position:sticky的节点,通常是最外层   * @param {object}     setting.fixedNode   当滚动一定距离时需要fixed在顶部的节点   * @param {int}      setting.top      fixed之后距离顶部的top值   * @param {int}      setting.zIndex     fixed之后的z-index值   * @param {string}     setting.fixedClazz   fixed时给fixedNode添加的类   * @param {function}   setting.runInScrollFn 滚动期间额外执行的函数   * @return {void}    */  Sticky.setting = {    stickyNode: null,    fixedNode: null,    top: 0,    zIndex: 100,    fixedClazz: '',    runInScrollFn: null  };  var sPro = Sticky.prototype;  var g = window;  /**   * 初始化   * @param {object} options 设置   * @return {void}        */  sPro.init = function(options){    this.setting = $.extend({}, Sticky.setting, options, true);    if (options.fixedNode) {      this.fixedNode = options.fixedNode[0] || options.fixedNode;      this.stickyNode = options.stickyNode[0] || options.stickyNode;      this.cssStickySupport = this.checkStickySupport();      this.stickyNodeHeight = this.stickyNode.clientHeight;      this.fixedClazz = options.fixedClazz;      this.top = parseInt(options.top, 10) || 0;      this.zIndex = parseInt(options.zIndex) || 1;      this.setStickyCss();      this.isfixed = false;      // 把改变定位的操作添加到节流函数与window.requestAnimationFrame方法中,确保一定事件内必须执行一次      this.onscrollCb = this.throttle(function() {        this.nextFrame(this.sticky.bind(this));      }.bind(this), 50, 100);      this.initCss = this.getInitCss();      this.fixedCss = this.getFixedCss();      this.addEvent();    }  };  /**   * 获取原始css样式   * @return {string} 定位的样式   */  sPro.getInitCss = function() {    if (!!this.fixedNode) {      return "position:" + this.fixedNode.style.position + ";top:" + this.fixedNode.style.top + "px;z-index:" + this.fixedNode.style.zIndex + ";";    }    return "";  };  /**   * 生成fixed时的css样式   * @return {void}   */  sPro.getFixedCss = function() {    return "position:fixed;top:" + this.top + "px;z-index:" + this.zIndex + ";";  };  /**   * 给fixedNode设置fixed定位样式   * @param {string} style fixed定位的样式字符串   */  sPro.setFixedCss = function(style) {    if(!this.cssStickySupport){      if (!!this.fixedNode){        this.fixedNode.style.cssText = style;      }    }  };  /**   * 检查浏览器是否支持positon: sticky定位   * @return {boolean} true 支持 false 不支持   */  sPro.checkStickySupport = function() {    var div= null;    if(g.CSS && g.CSS.supports){      return g.CSS.supports("(position: sticky) or (position: -webkit-sticky)");    }    div = document.createElement("div");    div.style.position = "sticky";    if("sticky" === div.style.position){      return true;    }    div.style.position = "-webkit-sticky";    if("-webkit-sticky" === div.style.position){      return true;    }    div = null;    return false;  };  /**   * 给sticyNode设置position: sticky定位   */  sPro.setStickyCss = function() {    if(this.cssStickySupport){      this.stickyNode.style.cssText = "position:-webkit-sticky;position:sticky;top:" + this.top + "px;z-index:" + this.zIndex + ";";    }  };  /**   * 监听window的滚动事件   */  sPro.addEvent = function() {    $(g).on('scroll', this.onscrollCb.bind(this));  };  /**   * 让函数在规定时间内必须执行一次   * @param {Function} fn   定时执行的函数   * @param {int}   delay 延迟多少毫秒执行   * @param {[type]}  mustRunDelay 多少毫秒内必须执行一次   * @return {[type]}   [description]   */  sPro.throttle = function(fn, delay, mustRunDelay){    var timer = null;    var lastTime;    return function(){      var now = +new Date();      var args = arguments;      g.clearTimeout(timer);      if(!lastTime){        lastTime = now;      }      if(now - lastTime > mustRunDelay){        fn.apply(this, args);        lastTime = now;      }else{        g.setTimeout(function(){          fn.apply(this, args);        }.bind(this), delay);      }    }.bind(this);  };  /**   * window.requestAnimationFrame的兼容性写法,保证在100/6ms执行一次   * @param {Function} fn 100/16ms需要执行的函数   * @return {void}      */  sPro.nextFrame = (function(fn){    var prefix = ["ms", "moz", "webkit", "o"];    var handle = {};    handle.requestAnimationFrame = window.requestAnimationFrame;    for(var i = 0; i < prefix.length && !handle.requestAnimationFrame; ++i){      handle.requestAnimationFrame = window[prefix[i] + "RequestAnimationFrame"];    }    if(!handle.requestAnimationFrame){      handle.requestAnimationFrame = function(fn) {        var raf = window.setTimeout(function() {          fn();        }, 16);        return raf;      };    }    return function(fn) {      handle.requestAnimationFrame.apply(g, arguments);    }  })();  /**   * 判断stickyNode的当前位置设置fixed|static|sticky定位   * @return {void}   */  sPro.sticky = function() {    this.setting.runInScrollFn && this.setting.runInScrollFn();    var stickyNodeBox = this.stickyNode.getBoundingClientRect();    if(stickyNodeBox.top <= this.top && !this.isfixed){      this.setFixedCss(this.fixedCss);      this.fixedClazz && $(this.fixedNode).addClass(this.fixedClazz);      this.isfixed = true;      $(this).trigger('onsticky', true);    } else if(stickyNodeBox.top > this.top && this.isfixed) {      this.setFixedCss(this.initCss.replace(/position:[^;]*/, "position:static"));      g.setTimeout(function() {        this.setFixedCss(this.initCss)      }.bind(this), 30);      this.fixedClazz && $(this.fixedNode).removeClass(this.fixedClazz);      this.isfixed = false;      $(this).trigger('onsticky', true);    }  };  $.initSticky = function(options){    return new Sticky(options);  };})();

html 结构:

  • 了解儿童编程
  • 参与公益直播课
  • 上传编程作品

css 结构:

.g-page-box .m-nav { height: 1.33333rem;}.g-page-box .m-nav .nav-fixed { height: .86667rem; padding: .22667rem .50667rem; background-color: #1aadbb; position: relative; transform: translate3d(0, 0, 0); -webkit-transform: translate3d(0, 0, 0); transition: height 4s;}.fixed {position: fixed;top: 0px;z-index: 100;}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:

  • js getBoundingClientRect使用方法详解
  • JS实现返回上一页并刷新页面的方法分析
  • js+HTML5 canvas 实现简单的加载条(进度条)功能示例
  • nodejs二进制与Buffer的介绍与使用
  • 2019年前端必用js正则(小结)
  • js获取对象,数组所有属性键值(key)和对应值(value)的方法示例


  • 上一条:
    koa2 从入门到精通(小结)
    下一条:
    JAVA面试题 static关键字详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 使用 Alpine.js 排序插件对元素进行排序(0个评论)
    • 在js中使用jszip + file-saver实现批量下载OSS文件功能示例(0个评论)
    • 在vue中实现父页面按钮显示子组件中的el-dialog效果(0个评论)
    • 使用mock-server实现模拟接口对接流程步骤(0个评论)
    • vue项目打包程序实现把项目打包成一个exe可执行程序(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客