<input type="text" class="height" placeholder="請輸入您的身高(公分)">
<input type="text" class="kg" placeholder="請輸入您的體重(公斤)">
<input type="button" class="send" value="計算">
<p class="total">您的 BMI 指數為
<span class="BMI">-</span>,
狀態是 <span class="status color">-</span></p>
.blue{
color: blue;
}
.green{
color: green;
}
.yellow{
color: yellow;
}
.orange{
color: orange;
}
.red{
color: red;
}
.purple{
color: purple;
}
const height = document.querySelector(".height");
const kg = document.querySelector(".kg");
const send = document.querySelector(".send");
const bmiDOM = document.querySelector(".BMI");
const statusDOM = document.querySelector(".status");
const BMIData = {
overLight: {
class: "blue",
statusText: "體重過輕"
},
normal: {
class: "green",
statusText: "正常"
},
overweight: {
class: "yellow",
statusText: "過重"
},
lOverweight: {
class: "orange",
statusText: "輕度肥胖"
},
mOverweight: {
class: "red",
statusText: "中度肥胖"
},
hOverweight: {
class: "purple",
statusText: "重度肥胖"
}
};
function calculationBMI() {
let thisHeight = parseInt(height.value);
let thisKg = parseInt(kg.value);
console.log(thisHeight, thisKg);
if (!isNaN(thisHeight) && !isNaN(thisKg)) {
let bmi = thisKg / (((thisHeight / 100) * thisHeight) / 100);
let status =
bmi >= 35
? "hOverweight"
: bmi >= 30
? "mOverweight"
: bmi >= 27
? "lOverweight"
: bmi >= 24
? "overweight"
: bmi >= 18.5
? "normal"
: "overLight";
render(status, bmi);
} else {
alert("請輸入正確身高體重格式喔");
};
}
function render(status, bmiText = "-") {
bmiDOM.textContent = bmiText;
statusDOM.textContent = BMIData[status] !== undefined ? BMIData[status].statusText : '-';
statusDOM.classList = BMIData[status] !== undefined ? BMIData[status].class : 'status';
}
send.addEventListener("click", calculationBMI);
height.addEventListener("keyup", render);
kg.addEventListener("keyup", render);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.