如何将html样式标签应用于条件语句



我对编码和html一无所知。

我正在尝试创建一种检测上限的计算器。例如,读取一个数字,如果它超过了数字20,方框应该突出显示红色

<head>
<title>Form</title>
<style> .red{
color: red;
}
</style>
</head>

<body>
<input type="number" placeholder="Length" id="length">
<input type="number" placeholder="Width" id="width">
<input type="number" placeholder="Height" id="height">
<input type="number" placeholder="Weight" id="weight">

<script>
function condition()
{
var len=document.getElementById("length").value);
var wid=document.getElementById("width").value);
var hei=document.getElementById("height").value);
var wei=document.getElementById("weight").value);
if (len >="20"){
<p class="red">This is some paragraph with red color.</p> //<<<This is where I have the issue. I do not know how to display the color after it is read and accepted.
}
</script>
<button type ="button" onclick="condition()">Calculate</button>
</body>
</html>

这就是你想要做的。如果你想让方框是红色的,只需将document.getElementById("target")更改为宽度或任何你需要的,然后在.red类中的样式中将color更改为border-color。之后,你需要制作一个重置机制,这样下次按下按钮时它就不会保持红色。

<!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>Document</title>
</head>
<body>
<style>
.red {
color: red;
}
</style>
<input type="number" placeholder="Length" id="length">
<input type="number" placeholder="Width" id="width">
<input type="number" placeholder="Height" id="height">
<input type="number" placeholder="Weight" id="weight">
<p id="target"></p>
<button type="button" onclick="condition()">Calculate</button>
<script>
function condition() {
let len = document.getElementById("length").value;
let wid = document.getElementById("width").value;
let hei = document.getElementById("height").value;
let wei = document.getElementById("weight").value;
if (len >= 20) {
let target = document.getElementById("target");
target.innerText = "This is some paragraph with red color.";
target.classList.add("red");
}
}
</script>
</body>
</html>

最新更新