JS - 无法读取 null 的 属性 'setAttribute'

JS - Cannot read property 'setAttribute' of null

我是 javascript 的新手,想编写 html 网站的 header。 JS: 当 window 宽度小于 1215px --> 左边部分变为 100% 宽度; header 的右半部分改为 0

我总是得到 "Cannot read property 'setAttribute' of null " 错误!

请帮忙! 代码:

if (window.innerWidth < 1215) {
    document.getElementById("#headerLeft").setAttribute("style", "width:100%");
    document.getElementById("#headerRight").setAttribute("style", "width:0%");
} else {
    document.getElementById("#headerLeft").setAttribute("style", "width:50%");
    document.getElementById("#headerRight").setAttribute("style", "width:50%");
}
body {
    margin:0;
}

header{
    height:100px;
    width:100%;
}

#headerLeft {
    background-color:#FF7043;
    height:100px;
    float:left;
}

#headerRight {
    background-color:#FFFFFF;
    height:100px;
    float:right;
}

.headerTitle {
    font-family:'Roboto', sans-serif;
    margin:15px;
    font-size:70px;
}

#headerRight .headerTitle {
    text-align:left;
    color:#FF7043;
    font-weight:300;
}

#headerLeft .headerTitle {
    text-align:center;
    color:#FFFFFF;
    font-weight:900;
}
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>example</title>
    
    <!-- css -->
    <link type="text/css" rel="stylesheet" href="style.css">
    
    <!-- fonts -->
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,500,700,900,100,300' rel='stylesheet' type='text/css'>
    
    <!-- javascripts -->
    <script language="javascript" type="text/javascript" src="script.js"></script>
    
</head> 
<body>
    <header>
        <div id="headerLeft">
            <p class="headerTitle">example</p>
        </div>
        
        <div id="headerRight">
            <p class="headerTitle">example</p>
        </div>
    </header>
    
    <nav>
    </nav>
    
    <main>
    </main>
    
    <footer>
    </footer>
</body>
</html>

这是因为您对 document.getElementById 的所有调用都找不到任何内容,因为没有任何元素具有这些 ID。看起来 jQuery 习惯在起作用,从您的 ID 中删除 #

首先按不带'#'的Id进行选择。 第二种是这样设置样式:

document.getElementById('').style.width = "20%";