input框根据数值范围字体颜色显示不同

发布于:2024-04-02 ⋅ 阅读:(68) ⋅ 点赞:(0)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Value Color Change</title>
    <style>
        /* Define your color classes as before */
        .input-color-red {
            color: red;
        }
        .input-color-green {
            color: green;
        }
        .input-color-blue {
            color: blue;
        }
        /* Add more classes for other colors as needed */
    </style>
</head>
<body>

<!-- Assume you have 30 input boxes with IDs "input1" to "input30" -->
<input type="text" id="input1" value="100">
<input type="text" id="input2" value="10">
<!-- ... and so on for the remaining inputs -->

<script>
    const inputRangeColors = [
        {
            id: 'TuoyanAI01',
            ranges: [
                { min: 0, max: 29.99, className: 'input-color-yellow' },
                { min: 30, max: 39.99, className: 'input-color-green' },
                { min: 40, max: Infinity, className: 'input-color-red' }
            ]
            id: 'input1',
            ranges: [
                { min: 0, max: 9, colorClass: 'input-color-red' },
                { min: 10, max: 19, colorClass: 'input-color-green' },
                { min: 20, max: Infinity, colorClass: 'input-color-blue' }
            ]
        },
        {
            id: 'input2',
            ranges: [
                { min: -5, max: 4, colorClass: 'input-color-red' },
                { min: 5, max: 14, colorClass: 'input-color-green' },
                { min: 15, max: Infinity, colorClass: 'input-color-blue' }
            ]
        },
    ];

    function applyInputColor(input, ranges) {
        const value = parseFloat(input.value);
        
        input.classList.remove(...ranges.flatMap(range => [range.colorClass]));
        
        const matchingRange = ranges.find(range => value >= range.min && value <= range.max);
        if (matchingRange) {
            input.classList.add(matchingRange.colorClass);
        }
    }
    
    inputRangeColors.forEach(({ id, ranges }) => {
        const input = document.getElementById(id);
        applyInputColor(input, ranges);

        input.addEventListener('input', function () {
            applyInputColor(this, ranges);
        });
    });
</script>
</body>
</html>
本文含有隐藏内容,请 开通VIP 后查看

网站公告


今日签到

点亮在社区的每一天
去签到