【每日一练】208—体重转换器的实现

每日一练1年前 (2023)发布 admin
1,354 0

第208练的最终效果:

【每日一练】208—体重转换器的实现

实现代码如下:

HTML:

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
    <title>第208练:</title>
    <link rel=”stylesheet” href=”index.css”>
</head>
<body>
    <div class=”container”>
        <h1 class=”heading”>体重转换器</h1>
        <div class=”input-container”>
            <label for=”pounds”>磅:</label>
            <input type=”number” id=”input” class=”input” step=”.1″ placeholder=”输入你的体重”>
        </div>
        <p>您的体重(kg)是:<span id=”result”></span></p>
        <p class=”error” id=”error”></p>
    </div>
    <script src=”index.js”></script>
</body>
</html>

CSS:

body{
    margin: 0;
    background: linear-gradient(to left top, yellow, lightblue, yellow);
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: ‘Courier New’, Courier, monospace;
    color: darkcyan;
}
.container{
    background: rgba(255,255,255,0.3);
    padding: 20px;
    box-shadow: 0 4px 10px rgba(0,0,0,.3);
    border-radius: 10px;
    width: 85%;
    max-width: 450px;
}
.input-container{
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: 700;
}
.input{
    padding: 10px;
    width: 70%;
    background: rgba(255,255,255,0.3);
    border-color: rgba(255,255,255,0.5);
    font-size: 18px;
    border-radius: 10px;
    color: darkgreen;
    outline: none;
}
.error{
    color: red;
}

JS:

const inputEl = document.getElementById(“input”);
const errorEl = document.getElementById(“error”);
const resultEl = document.getElementById(“result”);
let errorTime;
let resultTime;
function updateResults() {
  if (inputEl.value <= 0 || isNaN(inputEl.value)) {
    errorEl.innerText = “请输入有效数字”;
    clearTimeout(errorTime);
    errorTime = setTimeout(() => {
      errorEl.innerText = “”;
      inputEl.value = “”;
    }, 2000);
  } else {
    resultEl.innerText = (+inputEl.value / 2.2).toFixed(2);
    clearTimeout(resultTime);
    resultTime = setTimeout(() => {
      resultEl.innerText = “”;
      inputEl.value = “”;
    }, 10000);
  }
}
inputEl.addEventListener(“input”, updateResults);
© 版权声明

相关文章

暂无评论

暂无评论...