简单实现移动端输入价格键盘

HTML:

<div class="main">
    <div id="show-price">

    </div>
    <div class="keyboard">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
        <div>7</div>
        <div>8</div>
        <div>9</div>
        <div>.</div>
        <div>0</div>
        <div>删除</div>
    </div>
</div>

CSS:

.keyboard {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 240px;
    display: flex;
    flex-wrap: wrap;
}

.keyboard div {
    width: 30%;
    height: 50px;
    margin: 5px;
    text-align: center;
    line-height: 50px;
    border-radius: 5px;
    background: #eee;
}

JS:

<script src="../js/jquery-3.4.1.min.js"></script>
<script>
    window.onload = function () {
        let key = $('.keyboard div');
        let keyStr = ''
        key.click(function () {
            let str = ''
            let eleStr = $(this).html() == '删除' ? '' : $(this).html(); // 是否删除
            if(keyStr.length <= 0 && eleStr == '0') return; // 首位不能为0
            keyStr = keyStr + eleStr; // 拼接点击的数字
            if(eleStr == '') keyStr = keyStr.substr(0, keyStr.length - 1); // 删除
            for (let i = 0; i < keyStr.length; i++) { // 遍历
                if (keyStr[i] == '.') { // 判断是否为.
                    if (str.indexOf('.') == -1) str = str + keyStr[i]; // 是.并且其中不存在
                } else str = str + keyStr[i]; // 不是.就拼接
            }
            showPrice($('#show-price'), str); // 渲染
        })

        function showPrice(ele, str) {
            let htmlStr = ''
            for (let i = 0; i < str.length; i++) {
                htmlStr = htmlStr + `<span>${str[i]}</span>`
            }
            ele.html(htmlStr);
        }
    </script>

图片描述


Hoh_Xil
40 声望6 粉丝