自学内容网 自学内容网

就是这个样的粗爆,手搓一个计算器:热量计算器

       作为程序员,没有合适的工具,就得手搓一个,PC端,移动端均可适用。废话不多说,直接上代码。

HTML:

<div class="calculator">
<label for="weight">体重 (kg):</label> 
<input id="weight" step="0.1" type="number" placeholder="请输入您的体重"> 
<label for="height">身高 (cm):</label> 
<input id="height" step="0.1" type="number" placeholder="请输入您的身高"> 
<label for="age">年龄:</label> 
<input id="age" type="number" placeholder="请输入您的年龄"> 
<label for="gender">性别:</label>
<select id="gender">
<option value="male">男性</option>
<option value="female">女性</option>
</select>
<label for="activity">活动水平:</label>
<select id="activity">
<option value="1.2">很少运动</option>
<option value="1.375">轻量运动</option>
<option value="1.55">中度运动</option>
<option value="1.725">高度运动</option>
<option value="1.9">非常高强度运动</option>
</select>
<button onclick="calculateCalories()">计算</button>
<div class="result">
<p>每日所需热量:</p>
<p id="calories">0</p>
<p>千卡</p>
</div>
</div>

JS:

function calculateCalories() {
    const weight = parseFloat(document.getElementById('weight').value);
    const height = parseFloat(document.getElementById('height').value);
    const age = parseInt(document.getElementById('age').value);
    const gender = document.getElementById('gender').value;
    const activity = parseFloat(document.getElementById('activity').value);

    if (isNaN(weight) || isNaN(height) || isNaN(age) || weight <= 0 || height <= 0 || age <= 0) {
        alert('请输入有效的数值');
        return;
    }

    let bmr = 0; // 基础代谢率

    if (gender === 'male') {
        bmr = 88.36 + (13.4 * weight) + (4.8 * height) - (5.7 * age);
    } else {
        bmr = 447.6 + (9.2 * weight) + (3.1 * height) - (4.3 * age);
    }

    const calories = bmr * activity; // 每日所需热量

    document.getElementById('calories').textContent = calories.toFixed(2);
}

CSS:

.calculator {
    width: 300px;
    background-color: #333;
    color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}


label {
    display: block;
    margin-bottom: 10px;
    font-size: 16px;
}

input, select {
    width: 100%!important;
    padding: 10px!important;
    margin-bottom: 20px;
       color: #000000; 
    border-radius: 5px;
    border: 1px solid #555;
    font-size: 16px!important;
    background-color: #ffffff!important;
}

button {
    width: 100%;
    padding: 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: orange;
}

.result {
    margin-top: 20px;
    text-align: center;
}

option {
        background-color: #ffffff;
}


p {
    font-size: 18px;
        margin-top: 5px!important;
}

线上运行,可以直接打开:热量计算器


原文地址:https://blog.csdn.net/yuchangchenTT/article/details/143084503

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!