JS - 无法读取 null 的属性 'setAttribute'
JS - Cannot read property 'setAttribute' of null
我对javascript很陌生,想编写一个html网站的标题。JS:当窗口宽度小于 1215px 时 -->左侧部分变为 100% 宽度;标题的右侧部分为 0
我总是收到"无法读取空的属性'setAttribute'"错误!
请帮忙!法典:
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%";
相关文章:
- RegEx删除空属性?例如,如果(class=“”||class=“”)移除;否则就下课
- 全局变量和全局对象的属性之间有什么区别吗
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 如何在Bootstrap Modal中为动态点击生成的变量设置jade属性
- 序列化数据属性中对象的最可靠方法
- 分析高度属性时出现意外值{{specs.height}}.index.html
- TypeError:无法读取属性'推'未定义的JavaScript
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- AngularJS-使用'true'属性
- 可以't使用JavaScript获取width属性
- 未捕获的TypeError无法读取未定义的属性socialsharing
- TinyMCE->无法读取属性'setAttribute'为null
- Javascript setAttribute与jquery多属性setter
- 如何在IE8上使用setAttribute而不是使用style.cssText来更改样式属性
- 我应该使用 setAttribute 向元素添加属性吗?
- JS - 无法读取 null 的属性 'setAttribute'
- jQuery无法读取属性'setAttribute'的未定义
- 通过property或setAttribute设置属性
- IE9 错误:对象不支持属性或方法“setAttribute”
- 可以使用DOM's setAttribute函数设置多个属性吗?