WebAPIs-事件

Wenn 于 2022-09-06 发布

焦点事件

const input = document.querySelector('input')
//添加获取焦点事件
input.addEventListener('focus', fn1)
function fn1(){input.style.background = '#0ff';} //获取焦点时改变输入框背景颜色
//添加失去焦点事件
input.addEventListener('blur', fn2)
function fn2(){input.style.background = '';} //失去焦点时使输入框背景颜色为空

文本事件(输入事件)

const input = document.querySelector('input')
//添加文本事件
input.addEventListener('input', fn3)
function fn3(){console.log(input.value)} //输出文本框获取的值,实时获取

键盘事件

const doc = document.body  //下面两句作用相同,即获取文档本身
const doc = document.document.Element
const doc = document.body
doc.addEventListener('keydown', fn4) //键盘按下,即执行fn4,如果不抬起,则一直执行
function fn4(){console.log('down')}; 
doc.addEventListener('keyup', fn5) //键盘离开,执行fn5,默认为抬起状态,必然执行一次
function fn5(){console.log('up')};

事件对象

事件对象就是事件执行时产生的对象,调用函数的第一个参数,通常使用e标识

const div = document.querySelector('div')
div.addEventListener('click', fn6) //执行click事件时执行fn6函数
function fn6(e){console.log(e.type);} //输出事件对象e的类型

//获取鼠标位置,默认为坐上角为(x=0,y=0)
//clientX,clientY 对于浏览器窗口
function fn6(e){
    console.log(e.clientX,e.clientY); //输出事件对象e在浏览器左侧到鼠标点击的位置和浏览器上侧到鼠标点击的位置
}
//pageX,pageY 对于DOM文档
function fn6(e){
    console.log(e.pageX,e.pageY); //输出事件对象e在文档上的位置
}
//offsetX,offsetY //对于DOM当前元素
function fn6(e){
    console.log(e.offsetX,e.offsetY); //输出事件对象e在当前元素上的位置
}


const input = document.querySelector('input');
//获取键值
input.addEventListener('keydown',fn7)
function fn7(e){
    console.log(e.key); //输出键值
    //当键值等于`Enter`时输出`Publish`
    if (e.key === 'Enter'){console.log('Publish')};
    //使用keyCode获取键值,使用较少
    if (e.keyCode === '41H'){consloe.log('A')};
}

环境对象-this

简单来说,this指向调用该函数的对象,谁调用该函数,那this就指向谁

const div = document.querySelector('div')
div.addEventListener('click', fn8)
function fn8(){
    this.style.background = '#0ff'; //此时this指向div这个对象,因为是div调用
}

const btn = document.querySelector('.btn')
btn.addEventListener('click', fn9)
function fn9(){
    div.style.background = '#0dd';
    this.style.width = '200px'; //此时this指向btn,因为是btn调用这个函数
}

回调函数

给其他函数做参数即回调函数;接收回调函数当作参数的这个函数被称为高阶函数

                    function fn10(){
                        console.log('111')
                    }
                    function f11(n){
                        n();
                    }
                    f11(f10); //此时f11为高阶函数,f10为回调函数

箭头函数没有this,无法使用this