如果我想让box2在mouseon上将颜色更改为红色,那么使用setAttribute是否正确?

Jas*_*ang 1 javascript css dom

<html>
<head>
<title>Events!</title>

<!-- Loading my CSS -->
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div id="box-container">
    <div class="box" id="box1">I'm a box</div>
    <div class="box" id="box2">I'm a box</div>
    <div class="box" id="box3">I'm a box</div>
</div>

<div class="box" id="tricky-box">Tricky box</div>

<button id="secret-button">Super Secret</button>

<input id="secret-input"></input>

<!-- Ignore this stuff till later -->
<br>
<hr>
<hr>
<hr>
<br>

<div class="d1">1
    <div class="d2">2
        <div class="d3">3</div>
    </div>
</div>




<!-- Loading my JS -->
<script src="js/myapp.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

所以我希望box2在mouseon上将颜色改为红色,我想知道这是正确的:

 window.onload = function() {

 box2.onmouseover = function(event){
box2.setAttribute = ("style", "background-color: red;"); 
 }
Run Code Online (Sandbox Code Playgroud)

颜色没有改变.显然,我做错了什么.有谁知道这个问题?谢谢.

Ste*_*her 6

setAttribute 是一个方法,而不是一个对象属性.

您可以执行DOM样式对象:

box2.style.backgroundColor = "red";
Run Code Online (Sandbox Code Playgroud)

或正确的setAttribute方法:

box2.setAttribute("style","background-color:red");
Run Code Online (Sandbox Code Playgroud)

有关文档,请参阅MDN.