移动端css兼容问题

2,002 阅读2分钟

1.安卓使用绝对定位布局与原生input有冲突

如果绝对定位的元素在最下面,键盘弹起时,绝对定位元素会在键盘上面

解决办法:

  1. 使用flex布局实现,有一个flex-shrink可使用
  2. 或者监听resize事件,将元素隐藏

export function adapterPosition(selector) {
    if (/iphone/i.test(navigator.userAgent)) return
    const h = window.innerHeight;
    const dom = document.querySelector(selector)
    if (!dom) return
    const display = dom.style.display
    window.addEventListener('resize', () => {
        const height = window.innerHeight
        if (height < h) {
            dom.style.display = 'none'
        } else {
            dom.style.display = display
        }
    });
}

2.低版本浏览器,给input设置flex:1之后,将兄弟元素挤出了父元素空间

具体原因待查,反正需要给input加一个display:block

<div class="item">
    <div class="name">验证码</div>
    <input class="jInput input" type="number" pattern="[0-9]*" placeholder="请输入短信验证码">
    <button class="btn jSendVcodeBtn">
        发送验证码
    </button>
</div>

.item {
    margin-left: 15px;
    box-sizing: border-box;
    height: 60px;
    padding: 12px 15px 12px 0;
    overflow: hidden;
    background-color: #fff;
    color: #212121;
    position: relative;
    display: -webkit-box;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    border-bottom: 1px solid #f4f4f4;
    font-size: 16px;
}

.item .name {
    margin-right: 10px;
    min-width: 48px;
}

.item .input {
    display: block; // 需要加一个display:block
    outline: 0 none;
    -webkit-box-flex: 1;
    flex: 1;
    font-size: 16px;
    padding: 0;
    border-width: 0;
    box-shadow: none;
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    user-select: text;
}

3.relative top失效

关于relative元素top属性失效的原因,父元素没有设置高度,子元素top使用百分比的时候没有参照,此时可以使用px值

4.滚动穿透问题

描述:有场景需要mask,但是背景还是可以滚动,即滚动穿透,解决方案如下,主要是获取页面的滚动元素并设置其为fixed

body.no-scroll {
  position: fixed;
  width: 100%;
}
UtilFn.ModalHelper = function (bodyCls) {
    var scrollTop;
    var scrollingElement = document.scrollingElement || document.body; // 此写法兼容webkit,获取页面滚动元素
    return {
        afterOpen: function () {
            scrollTop = scrollingElement.scrollTop;
            document.body.classList.add(bodyCls);
            document.body.style.top = -scrollTop + 'px';
        },
        beforeClose: function () {
            document.body.classList.remove(bodyCls);
            scrollingElement.scrollTop = scrollTop;
        }
    };
}

5.浏览器对像素 四舍五入的问题

参考 web.jobbole.com/84113/

浏览器会对小数点进行四舍五入,实际渲染是四舍五入之后的,但是真实占用空间是原始大小,四舍五入的那部分值会影响下一个