You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML radio button表单自动计算并填充评分百分比?

实现Radio Button评分量规的自动填充功能

直接给你一个完整的可运行示例,复制到HTML文件里就能看到效果,完全贴合你的需求:

<!DOCTYPE html>
<html>
<head>
    <style>
        /* 评分区域样式 - 简单演示用 */
        .rating-container {
            width: 300px;
            height: 25px;
            border: 1px solid #ccc;
            margin-bottom: 20px;
            position: relative;
        }
        .rating-fill {
            height: 100%;
            background-color: #4CAF50;
            width: 0%;
            transition: width 0.3s ease;
        }
        .rating-text {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            text-align: center;
            line-height: 25px;
            font-size: 14px;
        }

        /* Radio按钮组样式 - 简单排版 */
        .radio-group {
            display: flex;
            gap: 15px;
        }
    </style>
</head>
<body>
    <!-- 顶部评分区域 -->
    <div class="rating-container">
        <div class="rating-fill" id="ratingFill"></div>
        <div class="rating-text" id="ratingText">0%</div>
    </div>

    <!-- Radio按钮表单 -->
    <form class="radio-group">
        <label><input type="radio" name="rating" value="10"> GO 10%</label>
        <label><input type="radio" name="rating" value="20"> GO 20%</label>
        <label><input type="radio" name="rating" value="50"> GO 50%</label>
        <label><input type="radio" name="rating" value="80"> GO 80%</label>
        <label><input type="radio" name="rating" value="100"> GO 100%</label>
    </form>

    <script>
        // 获取所有radio按钮和评分区域元素
        const radioButtons = document.querySelectorAll('input[name="rating"]');
        const ratingFill = document.getElementById('ratingFill');
        const ratingText = document.getElementById('ratingText');

        // 给每个radio按钮绑定切换事件
        radioButtons.forEach(radio => {
            radio.addEventListener('change', function() {
                // 拿到选中的百分比值
                const percentage = this.value + '%';
                // 更新填充条宽度
                ratingFill.style.width = percentage;
                // 更新文本显示
                ratingText.textContent = percentage;
            });
        });
    </script>
</body>
</html>

核心逻辑解释

  • HTML部分:

    • 所有radio按钮的name属性必须一致,确保单选效果
    • 每个radio的value设置对应百分比数值,方便JS直接读取使用
    • 评分区域用嵌套div实现:外层做背景容器,内层做动态填充的进度条,再叠加绝对定位的文本显示百分比
  • CSS部分:

    • 给填充条加过渡动画,让宽度变化更平滑自然
    • 文本绝对定位在容器中心,确保始终显示在填充条上方
  • JavaScript部分:

    • 监听radio按钮的change事件(切换选中状态时触发)
    • 读取当前选中radio的value,拼接成百分比字符串
    • 直接修改填充条的width样式和文本内容,实现实时更新

新手注意点

  1. 不需要复杂框架,原生HTML/CSS/JS就能搞定
  2. 调整样式直接修改CSS数值即可(比如容器宽度、填充条颜色)
  3. 要加默认选中项,给对应radio加checked属性,比如:<input type="radio" name="rating" value="20" checked>

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 03:45:55