【发布时间】:2022-11-29 21:00:23
【问题描述】:
当我使用 js 从 div 更改背景颜色时,它会在我的网站上更改它。 当我检查时,我看到 css 被内联添加,但它确实发生了变化 这是我在 js 文件中用来更改背景颜色的代码 我也在这个文件中制作了div 我还必须使用 js 和 setattribute,因为它用于学校任务 这是整个js文件
const div=document.createElement("div")
const h3=document.createElement("h3")
document.querySelector("main").appendChild(div)
div.appendChild(h3)
h3.innerHTML="Status"
div.id="status"
在这里我启动 div
document.getElementById("status").addEventListener("mouseover", () => document.getElementById("status").setAttribute("style", "background-color:black;"));
document.getElementById("status").addEventListener("mouseout", () => document.getElementById("status").removeAttribute("style"));
在这里我尝试改变背景颜色
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My Games</title>
<link type="text/css" href="styles/style.css" rel="stylesheet" />
<script tpye="text/javascript" src="js/dom.js" defer></script>
<script type="text/javascript" src="js/table-overview.js" defer></script>
</head>
<body>
<header>
<img src="images/logo.jpg" alt="Logo image of games" class="logo" />
<nav>
<ul>
<li class="actual">
<a href="index.html">Home</a>
</li>
<li>
<a href="overview.html">Overview</a>
</li>
<li><a href="table-overview.html">Table overview</a></li>
</ul>
</nav>
</header>
<main>
<h2>My Games</h2>
</main>
<footer>Wietse Gijbels: Front-end - 2022</footer>
</body>
</html>
*{
background-color: #00004f;
color: #fff;
text-align: center;
max-width: 800px;
margin: auto;
}
h2{
margin: 2em 0 ;
}
h3{
margin: 3em 0 1.5em 0
}
p{
margin: auto;
margin-bottom: 10px;
}
footer{
margin-top: 2em;
background-color: #000083;
padding: 10px 0;
border-radius: 10px;
}
【问题讨论】:
-
div来自哪里? -
不确定
setAttribute是否是一个好的选择,试试div.style.backgroundColor = 'black'代替。 (如果你想再次删除它,请设置transparent。)顺便说一句,为什么要使用 JS 来开始真正而不是 CSS 的工作? -
它用于学校练习,所以我必须用 setattribute 和 js 这样做
-
您需要发布一个最小的可重现示例,因为这只是一个需要通读的大杂烩。
-
@WietseGijbels 你能添加相关的html代码吗?
main来自哪里?
标签: javascript html sass