让前端飞web前端技术分享

jq 动态控制input输入的字体大小

2022-06-06  本文已影响0人  阿巳交不起水电费

需求描述:在固定宽度的输入框中输入文本,要求输入的文本全部显示出来。【注意:输入框宽度不变】

实现方案:因为谷歌浏览器默认最小字体12px,因此这里采用另一种方式transform:scale(xx)的方式。最后计算出具体缩放比例即可,为了让文本完全显示还需要动态设置input宽度,具体逻辑请看代码。

效果如下:

2.gif

代码如下:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            margin: 20px auto;
            width: 600px;
        }

        p {
            margin-bottom: 5px;
        }

        /*注意:input外面这个外层盒子很重要*/
        .inputBox {
            font-size: 10.5pt;
            width: 160px;
            height: 30px;
            line-height: 30px;
            padding: 0 5px;
            border: 1px solid #cccccc;
            box-sizing: border-box;
            position: relative;
            overflow: hidden;
        }

        input {
            outline: none !important;
            width: 100%;
            height: 100%;
            padding: 0;
            border: none;
            background: transparent;
            transform-origin: left;
        }
    </style>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div class="box">
    <p>输入文本,动态更新字体大小。</p>
    <p><span style="color: red;">注意:除了中文其他字符使用英文字符,符号用半角符号,不然计算不准确</span></p>
    <p>测试文本如:张三三,李四四,王五五,叶不凡,张三三</p>

    <div class="inputBox"><input id="input"/></div>
</div>
</body>
<script>
    $(function () {
        $('#input').on('input', hangeTextSize)

        // 判断是否是中文
        function isChinese(temp) {
            var re = /[^\u4E00-\u9FA5]/;
            if (re.test(temp)) return false;
            return true;
        }
        function hangeTextSize(e) {
            var val = e.target.value
//            console.log(val, $(this))

            var zhongWenNum = 0 // 中文个数
            var chartNum = 0 // 字符个数 - 占一半像素
            for (var i = 0; i < val.length; i++) {
                if (isChinese(val.charAt(i))) { // 判断当前字符是否是中文
                    zhongWenNum++
                } else {
                    chartNum++
                }
            }

            var fs = parseFloat($(this).css("font-size"))
            var width = $(this).parent().width() // 实际限制宽度

            // 根据字符计算的当前宽度
            var currentWidth = zhongWenNum * fs + chartNum * fs * 0.5
            currentWidth < width && (currentWidth = width)

            // 缩放比例
            var scale = width / currentWidth
            scale > 1 && (scale = 1)

            $(this).css({width: currentWidth + 'px', transform: 'scale(' + scale + ')'})
        }
    })
</script>
</html>

若对你有帮助,请点个赞吧,谢谢支持!
本文地址:https://www.jianshu.com/p/d9555f249768,转载请注明出处,谢谢。

上一篇下一篇

猜你喜欢

热点阅读