获得'无法读取null的属性样式'

Getting the 'cannot read property style of null'

本文关键字:属性 样式 null 获得 读取      更新时间:2023-09-26

请查看我的代码。我试了很多,但都没找到问题。如何防止将来出现此类错误?

<script>
var tbox= document.getElementById('tbox');
var selector= document.getElementById('selector');
function change(tothis){
    tbox.style.color=tothis;
}
function appear(){
    selector.style.visibility='visible';
    tbox.focus();
}
function disappear(){
    selector.style.visibility='hidden';
}
setTimeout(disappear,500);
</script>

错误表示tboxselector不存在。

document.getElementById('tbox');正在查找id为tbox:的元素

<p id="tbox"></p>

检查元素是否存在。如果它确实查看了代码及其在文档中的位置。如果脚本在head中,那么该元素还不存在。

确保您的代码在dom中的html元素之后,或者使用文档就绪块