Chr*_*rie 1 html javascript css
我想在单击按钮时更改第2行的背景颜色,但唯一改变的是整个背景.
function changeColor() {
document.body.style.backgroundColor = "black";
document.getElementByID("Div2").style.backgroundColor = "black";
}Run Code Online (Sandbox Code Playgroud)
<div id="Div2">
<div>Line 1</div>
<div2 class="line">Line 2</div2>
<div>Line 3</div>
<button onclick="changeColor()">Change color</button>Run Code Online (Sandbox Code Playgroud)
试试这个:
<div id = "Div2">
<div>Line 1</div>
<div id="line">Line 2</div>
<div>Line 3</div>
<button onclick="changeColor()">Change color</button>
<script>
function changeColor(){
var line = document.getElementById("line");
line.style.backgroundColor = "black";
line.style.color = "white";
}
</script>Run Code Online (Sandbox Code Playgroud)
你做错了几件事:
div2 不是有效的HTML标记getElementByID() 一定是 getElementById()getElementById()使用idas参数返回具有此id的元素.所以你必须给你的行一个id:<div id="line">Line 2</div>编辑:添加白色字体颜色