ios端input输入框光标延长问题

问题描述:输入框聚焦时,光标的长度不以输入框默认文字高度相等,而是延长至与input输入框父元素高度相等。同样的代码,在浏览器和Android都不会出现此问题,但是在ios的部分机型中出现了。

代码例子

<!DOCType html>
<html>

<head>
    <meta charset="utf-8">
    <style>
        .out-part {
            background-color: black;
            height: 50px;
            line-height: 50px;
            padding: 8px;
            box-sizing: border-box;
        }

        .panel {
            background-color: white;
            height: 30px;
            width: 200px;
            line-height: 30px;
        }

        .input {
            border: none;
            outline: none;
        }
    </style>
</head>

<body>
    <div class="out-part">
        <div class="panel">
            <input type="text" class="input" placeholder="请输入内容">
        </div>
    </div>
</body>

</html>

我们的代码结构及效果如上所示,咋看之下是没有问题的,但是如果用特定的ios机型(iPhone7)测试,图中的光标长度会直接顶到两边的白框。

原因分析:观察代码,发现input的高度是默认的,如下图所示

我们通过input的父元素(带有类为panel的div)定义空白的高度,以及通过line-height属性控制input居中,在一些ios机型中,光标的高度会跟随父元素的高度显示

解决方案:将父元素的高度设为auto,行高设为normal,针对input框控制其高度、行高样式将值设定为与font-size一致,如此一来光标的高度就会与输入框的输入字体高度相等,再通过margin使得输入框居中,如下代码:

<!DOCType html>
<html>

<head>
    <meta charset="utf-8">
    <style>
        .out-part {
            background-color: black;
            height: auto;
            line-height: normal;
            padding: 8px;
            box-sizing: border-box;
        }

        .panel {
            background-color: white;
            height: 30px;
            width: 200px;
            line-height: 30px;
        }

        .input {
            border: none;
            outline: none;
            height: 16px;
            line-height: 16px;
            font-size: 16px;
            margin: 5px 0;
        }
    </style>
</head>

<body>
    <div class="out-part">
        <div class="panel">
            <input type="text" class="input" placeholder="请输入内容">
        </div>
    </div>
</body>

</html>

最后感谢团队前辈的帮助,遇到这些兼容性问题有时还是挺难解决的,主要原因在于很难定位到具体问题。

posted @ 2021-04-20 23:59  JonnyOu1012  阅读(60)  评论(0编辑  收藏  举报