事件一

一.事件模式

内联模式

<button onclick="alert('666')">摁钮</button>

脚本模式

<button onclick="act()">
    摁钮
</button>
<script>
	function act () {
        console.log('666');
    }
</script>

二.事件组成

1>触发事件的元素节点对象 2>事件处理函数 (例:on+事件类型click) 3>事件执行函数

三.事件分类

1>鼠标事件

点击事件
click
双击事件
dbclick
按下
mousedown
弹起
mouseup
移进
mouseenter
mouseover 子元素也会触发
移出
mouseleave
mouseout 子元素也会触发
鼠标移动
mousemove

2>键盘事件

键盘按下
keydown
键盘弹起
keyup
按下字符触发 回车算字符
keypress 只识别字符键

3>HTML事件

窗口加载事件
load
窗口卸载事件
unload
HTML元素事件--表单的元素
获取焦点事件
focus
失去焦点事件
blur
选择
select
修改数据
触发 1.修改数据 2.失去焦点
change
输入数据
input
HTML元素事件--表单
数据提交
submit
数据重置
reset
滚动事件
具备滚动栏都可以添加
scroll

四.event事件源对象(window里的)

event对象是触发事件时,浏览器会通过事件对象作为参数隐藏传递过来

obj.conclick = function (e) {
    // argument[0]
	e = e || window.event //兼容写法 处理函数argument里只有一个参数
    console.log(e.altkey) //是否按下Alt
}

event属性

// 位置属性
obj.onclick = function (e) {
    console.log(e.x);  //窗口距离 不包含滚动栏距离 不推荐
 	console.log(e.y);  
    
	console.log(e.clientX);  // 窗口距离 不包含滚动栏距离 推荐
	console.log(e.offsetX);  // 鼠标离当前元素距离
 	console.log(e.pageX);  // 页面距离 包含滚动栏距离
   	console.log(e.layerX);  //定位的时候基于自己 不定位基于浏览器,包含不可见滚动栏距离
    console.log(e.screenX);  // 离屏幕x距离
// 按键属性 
    e.ctrlKey  
    e.shiftKey
    e.altKey  // alt是否按下
    e.button  // 鼠标按键 0 左键 1 滚轮 2 右键
    
  	e.type  // 事件触发类型
    
// target
    e.target  // 当前触发的对象
    e.currentTarget  // 当前加事件的对象 
}

键盘输入

window.onkeydown = function (e) {
	e = e || window.event;
	e.key  // 按键对应的ASCII码 有兼容问题
    e.keyCode  // 不管是大写还是小写都是大写的ASCII码 只支持字符 推荐使用
	// 将ASCII码转为字符串
    String.fromCharCode(e.keyCode)
}

window.onkeypress = function (e) {
    e = e || window.event;
    e.charCode  // 只在onkeypress下才能使用 返回ASCII码
}

五.事件委托机制

// 使用场景:有多个相同元素需要同样的事件
1.加事件给对应的父元素

2.在父元素的事件中进行判断 e.target
<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
<script>
    //事件委托 (里面有多个相同的元素需要同样的事件)
	//获取父元素 利用的父元素的事件及对应的e.target进行判断 当前你操作的元素是哪一个
	document.querySelector("ul").onclick = function(e){
    	e = e || window.event
    	if(e.target.nodeName == "LI"){
        //获取的节点名是大写
        	for(var j=0;j<this.children.length;j++){
            	this.children[j].style.backgroundColor = ""
        	}
        	e.target.style.backgroundColor = "pink"
    	}

	}
</script>
posted @ 2022-06-08 19:26  捧鱼咽  阅读(60)  评论(0)    收藏  举报