【问题标题】:Why can't I edit the style property with JavaScript?为什么我不能用 JavaScript 编辑样式属性?
【发布时间】:2019-10-10 15:16:24
【问题描述】:

所以,我只是想用 javascript 在 onkeyup 事件上显示一个<div>,但由于某种原因,它没有让我这样做,我得到了错误:

未捕获的类型错误:无法读取 null 的属性“样式”

这是我的代码:

HTML:

<div class="content" id="content" style="display: none">

Javascript:

function showContent() {
    document.getElementById('content').style.display = 'block';
}

你能帮忙吗?谢谢。

【问题讨论】:

标签: javascript html css tags frontend


【解决方案1】:

我猜你的函数是在你的块“内容”被添加到 DOM 之前调用的。

您可能希望在调用您的函数之前等待 DOM 准备好,或者通过如下按钮调用它:

function showContent() {
  document.getElementById('content').style.display = 'block';
}
.content {
  width: 200px;
  height: 100px;
  background: red;
}
<button onClick="showContent()">Show Block</button>

<div class="content" id="content" style="display: none">

【讨论】:

    猜你喜欢
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多