JS项目练习之求和(包含正则表达式验证)

发布时间:2019-07-14 22:00:12发布者:Mr.Zhang阅读(179)

最近在准备专升本,抽一点时间敷衍一下大家!!!嘿嘿嘿!!!

话不多说,上代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>求和练习</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        .cal-sum {
            width: 500px;
            margin: 100px auto;
        }
        .cal-sum input {
            width: 200px;
            height: 20px;
            padding: 0 5px;
            margin-right: 5px;
        }
        .cal-sum button {
            margin-top: 30px;
            width: 100px;
            height: 20px;
        }
        .cal-sum p {
            margin-top: 30px;
            font-size: 30px;
            color: red;
        }
    </style>
    <script type="text/javascript">
        window.onload = () => {
            const sumInput = document.getElementById('sum_input');
            const sumBtn = document.getElementById('sum_btn');
            const sumValue = document.getElementById('sum_value');

            // 确保输入框只能输入半角‘,’和数字
            // keyup事件,键盘抬起事件
            sumInput.addEventListener('keyup', () => {
                sumInput.value = sumInput.value.replace(/[^(\d)|(,)]/,"");
            });

            sumBtn.addEventListener('click', () => {
                let sum = 0;
                let inputNum = sumInput.value.split(',');
                for (let num in inputNum) {
                    sum += parseInt(inputNum[num]);
                }
                sumValue.innerHTML = sum;
            });
        }
    </script>
</head>
<body>
    <div class="cal-sum">
        <div><input type="text" value="1,2,3,4,5,6" id="sum_input"><span>求数字之和,数字之间用半角‘,’分隔</span></div>
        <button id="sum_btn">求和</button>
        <p><strong id="sum_value"></strong></p>    
    </div>
</body>
</html>

[注]在正则表达式中,^ 在 [] 中代表否定,在这个练习中意思就是:只要不是 ^ 和 数字,当键盘输入抬起后,会自动替换为没有,现象即自动会退回

放假了,也要抽点时间学习呀~~~~





本文转自博客园,原文地址:https://www.cnblogs.com/duxiu-fang/p/11185172.html