头部(无效果+解决)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Script位置</title>
<!-- IMPORT JS-->
<script>
//放置头部:可能导致无法获取到需要操作的元素
let box=document.getElementById('box');
console.log(box); //=>null
box.style.color='red'; //=>报错:未找到属性
//解决方法
//事件:当页面中的结构和内容都加载完成才会执行这里面的代码
//JQ中也有对应的方法$(document).ready(function(){})
window.onload=function(){
let box = document.getElementById('box');
console.log(box); //=>null
box.style.color = 'red'; //=>报错:未找到属性
}
</script>
</head>
<body>
<div id="box">Script位置</div>
</body>
</html>
底部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Script位置</title>
</head>
<body>
<div id="box">Script位置</div>
<!-- IMPORT JS-->
<script>
//防止底部:经常放到body最后面,是为了保证页面加载完成才去做这些事情
let box = document.getElementById('box');
console.log(box); //=>null
box.style.color = 'red'; //=>报错:未找到属性
</script>
</body>
</html>