JS 只是拒绝执行任何操作 - 不显示 console.log,不显示任何错误,不执行任何操作。
JS 真的没有给出任何生命迹象 - 我尝试制作 document.getelementbyid(box1)
和 ("#box") 和 ("box") 因为互联网上的人使用所有这些并且它有效。
尝试过在HTML中嵌入事件来调用函数,尝试过在window.onload上调用函数等
尝试更改文本和颜色以及大小和边距 - 没有任何效果。并且有时会出现 null 错误 - 这意味着 JS 由于某种原因无法获取样式值。
var box = document.getElementById("#box1");
function changeColor() {
var box = document.getElementById("#box1");
box.style.backgroundColor = 'red';
}
#box1 {
height: 100px;
width: 100px;
background-color: #B9E257;
}
#box2 {
height: 100px;
width: 100px;
background-color: #69ADE1;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="N.css" type="text/css">
</head>
<body>
<div id="box1">1</div>
<div id="box2">2</div>
<button onclick="changeColor()">Go!</button>
<script src="N.js" type="text/javascript"></script>
</body>
</html>
为什么它不起作用?
最佳答案
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
有关更多信息,请访问 docs
ID是区分大小写的字符串,在文档中是唯一的;
请检查下面的运行示例:
function changeColor() {
var box = document.getElementById("box1");
console.log(box);
box.style.backgroundColor = 'red';
}
#box1 {
height: 100px;
width: 100px;
background-color: #B9E257;
}
#box2 {
height: 100px;
width: 100px;
background-color: #69ADE1;
}
<head>
<link rel="stylesheet" href="N.css" type="text/css">
</head>
<body>
<div id="box1">1</div>
<div id="box2">2</div>
<button onclick="changeColor()">Go!</button>
<script src="N.js" type="text/javascript"></script>
</body>
关于javascript - JS函数不改变框颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56102205/