一,滚动事件和加载事件
- 添加屏幕滚动事件
- 当页面进行滚动时触发的事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
body {
height: 3000px;
background: linear-gradient(to bottom, red, blue);
}
.box {
width: 500px;
height: 200px;
border: 1px solid red;
/* 出现滚动条 */
overflow: scroll;
}
.son {
width: 500px;
height: 2000px;
background: linear-gradient(to bottom, red, blue);
}
</style>
</head>
<body>
<div class="box">
<div class="son"></div>
</div>
<script>
let box = document.querySelector('.box')
window.addEventListener('scroll', function () {
console.log('窗口在滚动');
})
box.addEventListener('scroll', function () {
console.log('小盒子在滚动');
})
document.addEventListener('scroll', function () {
console.log('窗口在滚动');
})
</script>
</body>
</html>
- 加载事件
- DOMContentLoaded:当页面文档全部被加载完毕之后,事件才触发,不需等待样式表和图片等资源,给document加
- load:监听整个页面资源,给window加
window.addEventListener('load', function () {}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script>
//当外部资源全部加载完毕之后才加载
window.addEventListener('load', function () {
console.log('加载中');
let p = document.querySelector('p')
let button = document.querySelector('button')
let img = document.querySelector('img')
p.addEventListener('load', function () {
console.log('正在加载中');
})
button.addEventListener('load', function () {
console.log('正在加载中');
})
img.addEventListener('load', function () {
console.log('正在加载中');
})
})
</script>
</head>
<body>
<div>
<p>我是p元素</p>
<button>我是按钮</button>
<img src="https://img1.baidu.com/it/u=1849701997,2238263017&fm=26&fmt=auto" alt="" />
</div>
</body>
</html>
二,元素大小和位置
1>. scroll家族: scrollWidth:可以获取元素的宽度(内容+padding),不包含滚动条(17)和边框,还可以获取卷去的距离--看不见的范围的距离
- 获取位置:获取元素内容往左,往上滚出去看不到的距离 【内容+padding】
<script>
window.addEventListener('load', function () {
let box = document.querySelector('.box')
console.log(box.scrollWidth);
})
</script>
- 获取页面垂直方向滚动出屏幕的距离
2>. offset家族:获取元素的自身宽高,包含元素自身设置的宽高,offsetTop:获取元素相对于定位父容器的垂直方向的距离,如果父容器没有定位,就参照最近的定位父容器,如果所有都有没有定位,就参照文档
- 获取位置:获取元素距离自己定位父级元素的左,上距离 【offsetWidth:内容 + padding + border】
3>. client家族:获取元素的可见部分宽高(不包含边框,滚动条等)
- 获取位置:获取左边框和上边框宽度
- clientLeft和clientTop 【内容 + padding】 4>. resize 会在窗口尺寸改变的时候触发
<style>
body {
background-color: red;
}
</style>
<script>
window.addEventListener('load', function() {
// 添加屏幕(视口)大小改变的监听
window.addEventListener('resize', function() {
document.body.style.backgroundColor = 'red'
let width = document.documentElement.clientWidth
if (width > 768) {
document.body.style.backgroundColor = 'green'
}
if (width > 992) {
document.body.style.backgroundColor = 'blue'
}
if (width > 1200) {
document.body.style.backgroundColor = 'black'
}
})
})
</script>
- 检测屏幕宽度