使用事件处理程序更改标题颜色



我正试图根据从下拉框选项中选择的内容将标题更改为不同的颜色。我正在使用JS来更新颜色,但它没有改变。

function changeStyle() {
var element = document.getElementById("changestyle");
element.style.color = "#FF0000";
}
#changestyle {
border: 1px solid #CCC;
width: 100px;
height: 100px;
}
<h1>Customize the Page</h1>
<form>
<p>Pick the color
<select id="TextColor" onchange="changestyle(color)">
<option value="r">Red</option>
<option value="g">Green</option>
<option value="p">Purple</option>
</select>
</p>
<input type="button" value="Update" onclick="header.style.changecolor">

你的代码中有几个bug,

正确的代码如下:

function changeStyle(color) {
var element = document.getElementById("header");
element.style.color = color;
}
document.querySelector('#btn').addEventListener('click', () => {
changeStyle(TextColor.value)
})
#changestyle {
border: 1px solid #CCC;
width: 100px;
height: 100px;
}
<h1 id="header">Customize the Page</h1>
<form>
<p>Pick the color
<select id="TextColor">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="purple">Purple</option>
</select>
</p>
<input type="button" value="Update" id="btn">
</form>

最新更新