【问题标题】:JS - Cannot read property 'setAttribute' of null [duplicate]JS - 无法读取 null 的属性“setAttribute”[重复]
【发布时间】:2016-01-15 19:56:03
【问题描述】:

我对 javascript 很陌生,想编写一个 html 网站的标题。 JS:当窗口宽度小于 1215px 时 --> 左边部分变为 100% 宽度;标题的右侧部分到 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>

【问题讨论】:

  • 不是你的问题的答案,但你可能想看看media queries

标签: javascript html css setattribute


【解决方案1】:

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

【讨论】:

  • 它看起来也运行得太快了......
  • 是的,脚本应该包含在页面的底部广告中,而不是在头部。或者它应该被包装在window.load 事件的 eventListener 中。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多