js cannot bind the event, Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') is resolved

I stepped on a small pit today, and when writing a vue project, I wanted to use the focus event to control the background transparency, but the event could not be registered

Let me talk about the reason first: javaScript finishes loading the DOM ahead of time.

Troubleshooting process : Use console.log() to print empty or not take effect directly. It is no problem when the js part is checked and it is confirmed. Check the class name and it is no problem.

That can only fix the DOM, that is, the js execution is finished, and the DOM has not been loaded yet.

Processing method : register the load event, and modify the style successfully.

/*
    一定要先注册load事件,等待DOM全部加载完成再给元素绑定事件。
    如果使用js设置背景颜色的话 必须使用 background-color
    background的话可能会出现修改样式不生效
*/

window.addEventListener('load', () => {
    const itemsTopFormDiv = document.querySelector('.itemsTopFormDiv')
    document.querySelector('.itemsTopFormInp').addEventListener('focus',function(e){
      e.target.style.backgroundColor = 'rgba(255,255,255,1)'
    })
    document.querySelector('.itemsTopFormInp').addEventListener('blur',function(e){
      e.target.style.backgroundColor = 'rgba(255,255,255,0)'
    })
});

Guess you like

Origin blog.csdn.net/guojixin12/article/details/131958473