解决ios 滚动后fixed失效问题

575 阅读2分钟

目的

通过h5去兼容解决ios中UIWebView不兼容fixed,导致滚动后fixed属性失效问题

解决方式

需要将html页面的头部header、底部footer、content进行隔离布局,父div(main)等于可视区高度,再根据需要去减footer、header的高度,并设置超出滚动。content就是我们的内容,当内容超出父级时,滚动区域只影响main,不影响到fixed区域的内容。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.3.4/vue.global.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .main {
        /*  若有header,减到header高度 */
        margin-top: 40px;
        /* 如果有header需要减掉header+footer的高度,如果没有就只减footer */
        height: calc(100vh - 100px);
        overflow-y: scroll;
      }
      .content {
        height: 1000px;
        background: aliceblue;
      }
      /* 底部 */
      .footer-tab {
        width: 100%;
        height: 60px;
        background: bisque;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
      }
      /* 头部tab */
      .header-tab {
        width: 100%;
        height: 40px;
        background: bisque;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
      }

      /* 修改滚动条的样式 */
      ::-webkit-scrollbar {
        width: 6px; /* 设置滚动条的宽度 */
        border-radius: 12px;
      }

      /* 滚动条的轨道 */
      ::-webkit-scrollbar-track {
        background-color: #f1f1f1; /* 设置滚动条的轨道背景色 */
      }

      /* 滚动条的滑块 */
      ::-webkit-scrollbar-thumb {
        background-color: #888; /* 设置滚动条的滑块背景色 */
      }

      /* 鼠标悬停在滚动条上时的滑块样式 */
      ::-webkit-scrollbar-thumb:hover {
        background-color: #555; /* 设置鼠标悬停时的滑块背景色 */
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div class="header-tab"></div>
      <div class="main">
        <div class="content"> {{msg}} </div>
      </div>
      <div class="footer-tab">
        <my-button></my-button>
      </div>
    </div>
  </body>
  <script type="text/javascript">
    const app = Vue.createApp({
      data() {
        return { msg: 'hello world' }
      }
    })

    app.component('my-button', {
      data() {
        return {
          str: 'btn'
        }
      },
      template: '<button>I am a {{str}}</button>'
    })
    app.mount('#app')
  </script>
</html>

缺点

  1. 如果想实现动态隐藏tab,顶部和底部会空白,又要根据需要适配一次。
  2. 每个h5页面都要进行适配,不友好,维护困难,长期成本高,治标不治本。

建议

  1. app内核浏览器升级成WKWebView,前端开发人员无需重复适配,可以愉快地使用fixed。