经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » CSS3 » 查看文章
移动端吸顶fixbar的解决方案详解
来源:jb51  时间:2019/7/17 11:02:02  对本文有异议

需求背景

经常会有这样的需求,当页面滚动到某一个位置时,需要某个页面元素固定在屏幕顶部,并且有时需要连续滚动吸顶。在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,它会固定在目标位置。

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

  1. position: -webkit-sticky;
  2. position: -moz-sticky;
  3. position: -ms-sticky;
  4. 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 事件都进行监听。

  1. // 注意处理遮罩层的位置
  2. var scrollHandler = function () {
  3. if (topLength < me.getScrollTop()) {
  4. target.css('position', 'fixed');
  5. me.replaceEle.show();
  6. }
  7. else {
  8. target.css('position', 'relative');
  9. me.replaceEle.hide();
  10. }
  11. };
  12. // 安卓情况下,防止惯性滚动引起的fix不及时的情况
  13. if (/(Android)/i.test(navigator.userAgent)) {
  14.  
  15. $(window).on('scroll', scrollHandler);
  16.  
  17. $(document.body).on('touchstart', scrollHandler);
  18. $(document.body).on('touchmove', scrollHandler);
  19. $(document.body).on('touchend', function () {
  20. scrollHandler();
  21. setTimeout(scrollHandler, 1000);
  22. });
  23. }

不支持sticky

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

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

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

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

原文代码

  1. (function() {
  2. function Sticky(){
  3. this.init.apply(this, arguments);
  4. }
  5. /**
  6. * 滚动fixed组件初始化
  7. * @param {object} setting allocate传进来的参数
  8. * @param {object} setting.stickyNode 需要设置position:sticky的节点,通常是最外层
  9. * @param {object} setting.fixedNode 当滚动一定距离时需要fixed在顶部的节点
  10. * @param {int} setting.top fixed之后距离顶部的top值
  11. * @param {int} setting.zIndex fixed之后的z-index值
  12. * @param {string} setting.fixedClazz fixed时给fixedNode添加的类
  13. * @param {function} setting.runInScrollFn 滚动期间额外执行的函数
  14. * @return {void}
  15. */
  16. Sticky.setting = {
  17. stickyNode: null,
  18. fixedNode: null,
  19. top: 0,
  20. zIndex: 100,
  21. fixedClazz: '',
  22. runInScrollFn: null
  23. };
  24. var sPro = Sticky.prototype;
  25. var g = window;
  26. /**
  27. * 初始化
  28. * @param {object} options 设置
  29. * @return {void}
  30. */
  31. sPro.init = function(options){
  32. this.setting = $.extend({}, Sticky.setting, options, true);
  33. if (options.fixedNode) {
  34. this.fixedNode = options.fixedNode[0] || options.fixedNode;
  35. this.stickyNode = options.stickyNode[0] || options.stickyNode;
  36. this.cssStickySupport = this.checkStickySupport();
  37. this.stickyNodeHeight = this.stickyNode.clientHeight;
  38. this.fixedClazz = options.fixedClazz;
  39. this.top = parseInt(options.top, 10) || 0;
  40. this.zIndex = parseInt(options.zIndex) || 1;
  41. this.setStickyCss();
  42. this.isfixed = false;
  43. // 把改变定位的操作添加到节流函数与window.requestAnimationFrame方法中,确保一定事件内必须执行一次
  44. this.onscrollCb = this.throttle(function() {
  45. this.nextFrame(this.sticky.bind(this));
  46. }.bind(this), 50, 100);
  47. this.initCss = this.getInitCss();
  48. this.fixedCss = this.getFixedCss();
  49. this.addEvent();
  50. }
  51. };
  52. /**
  53. * 获取原始css样式
  54. * @return {string} 定位的样式
  55. */
  56. sPro.getInitCss = function() {
  57. if (!!this.fixedNode) {
  58. return "position:" + this.fixedNode.style.position + ";top:" + this.fixedNode.style.top + "px;z-index:" + this.fixedNode.style.zIndex + ";";
  59. }
  60. return "";
  61. };
  62. /**
  63. * 生成fixed时的css样式
  64. * @return {void}
  65. */
  66. sPro.getFixedCss = function() {
  67. return "position:fixed;top:" + this.top + "px;z-index:" + this.zIndex + ";";
  68. };
  69. /**
  70. * 给fixedNode设置fixed定位样式
  71. * @param {string} style fixed定位的样式字符串
  72. */
  73. sPro.setFixedCss = function(style) {
  74. if(!this.cssStickySupport){
  75. if (!!this.fixedNode){
  76. this.fixedNode.style.cssText = style;
  77. }
  78. }
  79. };
  80. /**
  81. * 检查浏览器是否支持positon: sticky定位
  82. * @return {boolean} true 支持 false 不支持
  83. */
  84. sPro.checkStickySupport = function() {
  85. var div= null;
  86. if(g.CSS && g.CSS.supports){
  87. return g.CSS.supports("(position: sticky) or (position: -webkit-sticky)");
  88. }
  89. div = document.createElement("div");
  90. div.style.position = "sticky";
  91. if("sticky" === div.style.position){
  92. return true;
  93. }
  94. div.style.position = "-webkit-sticky";
  95. if("-webkit-sticky" === div.style.position){
  96. return true;
  97. }
  98. div = null;
  99. return false;
  100. };
  101. /**
  102. * 给sticyNode设置position: sticky定位
  103. */
  104. sPro.setStickyCss = function() {
  105. if(this.cssStickySupport){
  106. this.stickyNode.style.cssText = "position:-webkit-sticky;position:sticky;top:" + this.top + "px;z-index:" + this.zIndex + ";";
  107. }
  108. };
  109. /**
  110. * 监听window的滚动事件
  111. */
  112. sPro.addEvent = function() {
  113. $(g).on('scroll', this.onscrollCb.bind(this));
  114. };
  115. /**
  116. * 让函数在规定时间内必须执行一次
  117. * @param {Function} fn 定时执行的函数
  118. * @param {int} delay 延迟多少毫秒执行
  119. * @param {[type]} mustRunDelay 多少毫秒内必须执行一次
  120. * @return {[type]} [description]
  121. */
  122. sPro.throttle = function(fn, delay, mustRunDelay){
  123. var timer = null;
  124. var lastTime;
  125. return function(){
  126. var now = +new Date();
  127. var args = arguments;
  128. g.clearTimeout(timer);
  129. if(!lastTime){
  130. lastTime = now;
  131. }
  132. if(now - lastTime > mustRunDelay){
  133. fn.apply(this, args);
  134. lastTime = now;
  135. }else{
  136. g.setTimeout(function(){
  137. fn.apply(this, args);
  138. }.bind(this), delay);
  139. }
  140. }.bind(this);
  141. };
  142. /**
  143. * window.requestAnimationFrame的兼容性写法,保证在100/6ms执行一次
  144. * @param {Function} fn 100/16ms需要执行的函数
  145. * @return {void}
  146. */
  147. sPro.nextFrame = (function(fn){
  148. var prefix = ["ms", "moz", "webkit", "o"];
  149. var handle = {};
  150. handle.requestAnimationFrame = window.requestAnimationFrame;
  151. for(var i = 0; i < prefix.length && !handle.requestAnimationFrame; ++i){
  152. handle.requestAnimationFrame = window[prefix[i] + "RequestAnimationFrame"];
  153. }
  154. if(!handle.requestAnimationFrame){
  155. handle.requestAnimationFrame = function(fn) {
  156. var raf = window.setTimeout(function() {
  157. fn();
  158. }, 16);
  159. return raf;
  160. };
  161. }
  162. return function(fn) {
  163. handle.requestAnimationFrame.apply(g, arguments);
  164. }
  165. })();
  166. /**
  167. * 判断stickyNode的当前位置设置fixed|static|sticky定位
  168. * @return {void}
  169. */
  170. sPro.sticky = function() {
  171. this.setting.runInScrollFn && this.setting.runInScrollFn();
  172. var stickyNodeBox = this.stickyNode.getBoundingClientRect();
  173. if(stickyNodeBox.top <= this.top && !this.isfixed){
  174. this.setFixedCss(this.fixedCss);
  175. this.fixedClazz && $(this.fixedNode).addClass(this.fixedClazz);
  176. this.isfixed = true;
  177. $(this).trigger('onsticky', true);
  178. } else if(stickyNodeBox.top > this.top && this.isfixed) {
  179. this.setFixedCss(this.initCss.replace(/position:[^;]*/, "position:static"));
  180. g.setTimeout(function() {
  181. this.setFixedCss(this.initCss)
  182. }.bind(this), 30);
  183. this.fixedClazz && $(this.fixedNode).removeClass(this.fixedClazz);
  184. this.isfixed = false;
  185. $(this).trigger('onsticky', true);
  186. }
  187. };
  188. $.initSticky = function(options){
  189. return new Sticky(options);
  190. };
  191. })();

html 结构:

  1. <div class="m-nav">
  2. <div class="nav-fixed fixed" id="j-nav" style="position: fixed; top: 0px; z-index: 100;">
  3. <ul class="f-cb">
  4. <li class="active" anchor-id="j-understand">了解儿童编程</li>
  5. <li anchor-id="j-join">参与公益直播课</li>
  6. <li anchor-id="j-upload">上传编程作品</li>
  7. </ul>
  8. </div>
  9. </div>

css 结构:

  1. .g-page-box .m-nav {
  2. height: 1.33333rem;
  3. }
  4.  
  5. .g-page-box .m-nav .nav-fixed {
  6. height: .86667rem;
  7. padding: .22667rem .50667rem;
  8. background-color: #1aadbb;
  9. position: relative;
  10. transform: translate3d(0, 0, 0);
  11. -webkit-transform: translate3d(0, 0, 0);
  12. transition: height 4s;
  13. }
  14.  
  15. .fixed {
  16. position: fixed;
  17. top: 0px;
  18. z-index: 100;
  19. }

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号