javascript - JS函数不改变框颜色

标签 javascript html css

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/

相关文章:

javascript - 在输入类型文本中将小数点右对齐

javascript:window.open 打开图像,它可以工作,但也会更改第一页

javascript - IBM Worklight - 使用 jQuery 进行表单验证

javascript - 我想为每个滚动CSS更改文本

html - 根据基础网格中的兄弟对齐行

html - 表格中的 Css、gif、视口(viewport)高度的 100%

javascript - 如何从push() firebase中提取id?

javascript - jQuery 对象是真正的 DOM 对象吗?给它们添加属性是否正确?

css - 在文本旁边显示物化图标?

javascript - 调试 Javascript 幻灯片