环境对象
环境对象指的是函数内部特殊的变量this,他代表当前函数运行时所处的环境
谁调用,this就指向谁
回调函数
如果将函数A作为参数传递给函数B,则称A为回调函数
// input中所有被选中的
input:checked
事件流
- 事件捕获
从dom的根元素开始执行对应事件(从外到里)dom.addEventListener(事件类型,事件处理函数,是否使用捕获机制) <!-- 第三个参数为true代表捕获阶段触发,false代表冒泡阶段,不写默认false -->
- 冒泡
从下到上调用所有父级元素的同名事件<script> const fa = document.querySelector('.fa'); const son = document.querySelector('.son'); document.addEventListener('click', function(){ alert('我是爷爷') }) fa.addEventListener('click', function(){ alert('我是爸爸') }) son.addEventListener('click', function(){ alert('我是孙子') }) </script>
阻止冒泡
- 前提:拿到事件对象
- 语法,该方法可以阻止冒泡也可阻止捕获
事件对象.stopPropagation()
son.addEventListener('click', function(e){ alert('我是孙子') e.stopPropagation() })
解绑事件
匿名函数无法被解绑
btn.removeEventListener(事件类型,事件处理函数,[获取捕获或者冒泡阶段])
鼠标效果
- mouseover mouseout 有冒泡效果
- mouseenter mouseleave 没有冒泡效果(推荐)
事件委托
- 利用事件冒泡特点
- 给父元素注册事件
- 子元素不注册,当触发子元素时则会冒泡到父元素身上,从而触发父元素
const ul = document.querySelector('ul')
ul.addEventListener('click',function (e) {
console.log(e);
// this.style.color='pink'
// 得到所点击的元素——事件对象
e.target.style.color='#22c3c3'
})
事件对象.target.tagName获取点击的对象
阻止默认行为
事件对象.preventDefault()
页面加载事件
// 监听页面所有资源加载完毕再执行回调函数
window.addEventListener('load', function(){})
// 当初始的HTML文档被全部加载和解析完成之后,DOMContentLoaded事件触发无需等待样式表,图像完全加载
document.addEventListener('DOMContentLoaded', function(){})
元素滚动事件
滚动条在滚动时触发
- scrollTop:检测滚动条上下滚动的距离
- scrollLeft:监测滚动条左右滚动的距离
- scrollTo(0,100):把内容滚动到指定坐标
获取html标签
document.documentElement
document.documentElement.scrollTop必须写到函数内
得到的数据是数字型 不带单位 可读写
页面尺寸事件
- resize:浏览器窗口大小发生变化时触发
元素.addEventListener('resize', function(){})
- clientWidth和clientHeight获取元素宽高,不包含边框和滚动条
元素尺寸与位置
- 获取宽高
- offsetWidth和offsetHeight
- 获取元素自生宽高包含元素自身设置的宽高、padding、border
- 取出来的是数值方便计算
- 如果盒子隐藏获取结果为0
- 获取位置
- offestLeft offsetTop
- 只读属性
- 获取元素距定位父级元素的左、上距离
- 获取元素距可是窗口位置
- getBoundingClientRect()
控制滚动页面的两种方法
// 1
window.scrollTo(x,y)
// 2
document.documentElement.scrollTop=距离
为页面添加滑动效果
html{
scroll-behavior: smooth;
}
属性选择器
<style>
input{
color:red;
}
</style>
<input type="text" value="134">
<input type="password" >
此时两个input中的内容都会变红
当加上属性选择器后,只有有value属性的input会变红
<style>
input[value]{
color:red;
}
</style>
<input type="text" value="134">
<input type="password" >
自定义属性也可以使用属性选择器
<input type="text" value="134" data-id="0" data-name="submit">
<input type="password" >
<script>
const input =document.querySelector("input[value]");
console.log(input);
console.log(input.dataset);//自定义属性集合
</script>
t type="password" >
<script>
const input =document.querySelector("input[value]");
console.log(input);
console.log(input.dataset);//自定义属性集合
</script>