iOS下的 Fixed + Input 调用键盘的时候fixed无效问题解决方案

https://www.haorooms.com/post/ios_fixed_inputhtml

作touchweb开发的时候,作头疼的是,电脑上面时候好的,有些手机上面也是好的,个别手机和浏览器出现问题,对于这些,只能慢慢调试,找问题。前端

今天说一下比较老的IOS的问题,那就是“iOS下的 Fixed + Input 调用键盘的时候fixed无效问题”。ios

案例以下

<body class="layout-fixed">
    <!-- fixed定位的头部 -->
    <header>

    </header>

    <!-- 能够滚动的区域 -->
    <main>
        <!-- 内容在这里... -->
    </main>

    <!-- fixed定位的底部 -->
    <footer>
        <input type="text" placeholder="Footer..."/>
        <button class="submit">提交</button>
    </footer>
</body>

对应的样式以下:web

header, footer, main {
    display: block;
}

header {
    position: fixed;
    height: 50px;
    left: 0;
    right: 0;
    top: 0;
}

footer {
    position: fixed;
    height: 34px;
    left: 0;
    right: 0;
    bottom: 0;
}

main {
    margin-top: 50px;
    margin-bottom: 34px;
    height: 2000px
}

而后看起来就是下面这个样子。拖动页面时 header 和 footer 已经定位在了对应的位置,目测没问题了。浏览器

enter image description here

但接下来问题就来了!若是底部输入框软键盘被唤起之后,再次滑动页面,就会看到以下图所示:布局

enter image description here

咱们看到 fixed 定位好的元素跟随页面滚动了起来… fixed 属性失效了!post

这是为何呢?简单解释下: > 软键盘唤起后,页面的 fixed 元素将失效(即没法浮动,也能够理解为变成了 absolute 定位),因此当页面超过一屏且滚动时,失效的 fixed 元素就会跟随滚动了。测试

这即是 iOS 上 fixed 元素和输入框的 bug 。其中不只限于 type=text 的输入框,凡是软键盘(好比时间日期选择、select 选择等等)被唤起,都会遇到一样地问题。spa

虽然 isScroll.js 能够很好的解决 fixed 定位滚动的问题,可是不在万不得已的状况下,咱们尽可能尝试一下不依赖第三方库的布局方案,以简化实现方式。这里抛砖引玉做为参考。调试

解决思路

既然在 iOS 下因为软键盘唤出后,页面 fixed 元素会失效,致使跟随页面一块儿滚动,那么假如——页面不会过长出现滚动,那么即使 fixed 元素失效,也没法跟随页面滚动,也就不会出现上面的问题了。

那么按照这个思路,若是使 fixed 元素的父级不出现滚动,而将原 body 滚动的区域域移到 main 内部,而 header 和 footer 的样式不变,代码以下:

<body class="layout-scroll-fixed">
    <!-- fixed定位的头部 (absolute绝对定位也能够)-->
    <header>

    </header>

    <!-- 能够滚动的区域 -->
    <main>
        <div class="content">
        <!-- 内容在这里... -->
        </div>
    </main>

    <!-- fixed定位的底部 (absolute绝对定位也能够)-->
    <footer>
        <input type="text" placeholder="Footer..."/>
        <button class="submit">提交</button>
    </footer>
</body>
header, footer, main {
    display: block;
}

header {
    position: fixed;//或者absolute
    height: 50px;
    left: 0;
    right: 0;
    top: 0;
}

footer {
    position: fixed;//或者写成absolute
    height: 34px;
    left: 0;
    right: 0;
    bottom: 0;
}

main {
/* main绝对定位,进行内部滚动 */
position: absolute;
top: 50px;
bottom: 34px;
/* 使之能够滚动 */
 overflow-y: scroll;
  /* 增长该属性,能够增长弹性,是滑动更加顺畅 */
  -webkit-overflow-scrolling: touch;   
}

main .content {
    height: 2000px;
}

另外,这里的 header 和 footer 使用的是 fixed 定位,若是考虑到更老一些的 iOS 系统不支持 fixed 元素,彻底能够把 fixed 替换成 absolute 。测试后效果是同样的。

按照上面布局,就不会出现问题了!

另一种方案

这个方案是最近在网上看到的,我没有使用过,可是看到案例是没有问题的,感兴趣的能够去看下,我在前端资源库中已经发布了这个方案。

地址以下:http://resource.haorooms.com/softshow-16-151-1.html

欢迎访问留言!

相关文章
相关标签/搜索