要在单击按钮时更改标签的新背景颜色,您可以使用JavaScript和HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Color</title>
</head>
<body>
<label for="color">Choose a color:</label>
<input type="color" id="color" name="color">
<button onclick="changeLabelColor()">Change Label Color</button>
<p id="text">This is a text label.</p>
<script>
function changeLabelColor() {
const colorInput = document.getElementById('color');
const textLabel = document.getElementById('text');
textLabel.style.backgroundColor = colorInput.value;
}
</script>
</body>
</html>
在这个示例中,我们使用了HTML <input type="color">
元素让用户选择颜色。当用户单击按钮时,changeLabelColor()
函数会被调用。函数会获取用户所选颜色,并使用 textLabel.style.backgroundColor
更改 <p>
标签的背景颜色。
领取专属 10元无门槛券
手把手带您无忧上云