一:环境对象
阅读完本小节能够判断函数运行在不同环境中,this所指代的对象
1 什么是环境对象
环境对象是函数中的this变量,代表当前函数运行时所处的环境
2 this指向问题
粗略判断规则:谁调用函数,this就指向谁
<script>
function fn() {
console.log(this);//window
}
fn()
const tx = document.querySelector('input')
tx.addEventListener('input', function (e) {
console.log(this);//input
})
</script>
3 this的简单应用
<button>点我</button>
<script>
const tx = document.querySelector('button')
tx.addEventListener('click', function (e) {
// console.log(this);
this.style.backgroundColor = 'red'
})
</script>
//因为this由button,所以通过这种方式;点击button按钮后,
//button背景颜色改变
二:回调函数
1 什么是回调函数
将函数A作为参数传递给函数B,称函数A为回调函数
回调函数本质也是函数,只不过将因为其作为参数传递给别的函数;通过先执行某一操作后调用,随后函数才运行,所以称为回调函数
2 回调函数使用场景
function fn(){
console.log('我是回调')
}
setInterval(fn,1000)
box.addEventListener('click',function(){
console.log('我是回调')
})
三:综合案例(Tab栏切换)
需求:鼠标经过不同的选项卡,底部可以显示不同内容
1 鼠标经过超链接a实现变色效果
// 1 鼠标经过实现超链接变色
const colorA = document.querySelectorAll('.tab-nav a')
for (let i = 0; i < colorA.length; i++) {
colorA[i].addEventListener('mouseenter', function () {
//遍历a为每个a添加
//排他思想
document.querySelector('.tab-nav .active').classList.remove('active')
this.classList.add('active')
}
)
}
重点:
- 排他思想的应用
- for循环遍历思想
2 鼠标滑动实现盒子显示隐藏
//2 实现盒子的显示和隐藏
document.querySelector('.tab-content .active').classList.remove('active')
img[i].classList.add('active')