一、页面加载事件
页面加载事件有哪两个?如何添加?
> load 事件:监听整个页面资源给window加
> DOMContentLoaded:给 document加DOMContentLoaded事件,无需等待样式表、图像等完全加载,速度更快
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 等待页面所有资源加载完毕,就回去执行回到函数 -->
<script>
// window.addEventListener('load', function () {
// const btn = document.querySelector('button')
// btn.addEventListener('click', function () {
// console.log('点击了');
// })
// })
// 等待图片资源加载完毕,再去执行里面的代码
// img.addEventListener('load', function () {
// console.log('图片');
// })
document.addEventListener('DOMContentLoaded', function () {
const btn = document.querySelector('button')
btn.addEventListener('click', function () {
alert(11)
})
})
</script>
</head>
<body>
<button>点击</button>
</body>
</html>
二、页面滚动事件——滚动条在滚动的时候持续触发的事件
1. 应用场景:很多页面需要检测用户把页面滚动到某个区域后做一些处理,比如固定导航栏、返回顶部等。
2. 事件名:scroll ——给window或document添加scroll事件
3. 页面滚动事件-获取位置
scrollLeft(被卷去的左侧)和scrollTop(被卷去的头部) (属性)
> 获取被卷去的大小
> 获取元素内容往左、往上滚出去看不到的距离
> 这两个值是可读写的
<script>
const div = document.querySelector('div')
// 监听整个页面滚动
window.addEventListener('scroll', function () {
// 页面滑动了多少像素,被卷去了多少
// 获取html元素写法:document.documentElement
// console.log(document.documentElement.scrollTop);
// 为什么写到里面?——页面一滑动要取最新的值,写到外面的话取到的值会一直为0
const n = document.documentElement.scrollTop
// 大于等于100时显示,否则隐藏
if (n >= 100) {
div.style.display = 'block'
}
else { div.style.display = 'none' }
})
// const div = document.querySelector('div')
// div.addEventListener('scroll', function () {
// // scrollTop:被卷去的头部
// console.log(div.scrollTop);
// })
</script>