鼠标事件
click - 单击
contextmenu - 右击
window.oncontextmenu = function(){
alert(123)
}
鼠标按下 - mousedown
var box = document.querySelector('.box')
box.onmousedown = function(){
console.log(3251)
}
鼠标抬起 - mouseup
box.onmouseup = function(){
console.log(123);
}
移入移出 - mouseover mouseout / mouseenter mouseleave
- mouseover mouseout
var small = document.querySelector('.small')
box.onmouseenter = function(){
console.log("大的进来了");
}
box.onmouseleave = function(){
console.log("大的出去了");
}
small.onmouseenter = function(){
console.log("小的进来了");
}
small.onmouseleave = function(){
console.log("小的出去了");
}
- mouseenter mouseleave
box.onmouseover = function(){
console.log("大的进来了");
}
box.onmouseout = function(){
console.log("大的出去了");
}
small.onmouseover = function(){
console.log("小的进来了");
}
small.onmouseout = function(){
console.log("小的出去了");
}
鼠标移动事件 - mousemove
box.onmousemove = function(){
console.log("移动了");
}
滚轮事件 - mousewheel
window.onmousewheel = function(){
console.log("滚动了");
}
键盘敲击的事件 - keypress
window.onkeypress = function(){
console.log("按下了键盘");
}
表单的input事件 - 实时监听input文本框的内容
var input = document.querySelector('input')
var textBox = document.querySelector('.text')
input.oninput = function(){
textBox.innerText = this.value;
}
事件流
事件流包含3个阶段:捕获阶段、目标阶段、冒泡阶段
事件侦听器
-事件侦听器 : 元素.addEventListener(事件类型,函数,布尔值-是否在捕获阶段执行,默认是false)
同类型事件可以绑定多次
box.addEventListener('click',function(){
console.log("第一次");
})
box.addEventListener('click',function(){
console.log("第二次");
})
可以让其他元素事件在捕获阶段执行
box.addEventListener('click',function(){
console.log("大");
},true)
var small = document.querySelector('.small')
small.addEventListener('click',function(){
console.log("小");
})
// 事件侦听器在低版本ie中不兼容
// 在低版本ie中事件流只有两个阶段,目标阶段和冒泡阶段,没有捕获阶段
// 元素.attachEvent(on事件类型,函数)
- 兼容的绑定事件的函数
function bindEvent(ele,type,fn){
if(ele.addEventListener){
ele.addEventListener(type,fn)
}else{
ele.attachEvent('on'+type,fn)
}
}
function f(){
console.log("点击了");
}
function f1(){
console.log("第二次点击了");
}
bindEvent(box,'click',f)
bindEvent(box,'click',f1)
事件解绑
事件解绑 - 删除掉事件
var box = document.querySelector('.box')
function fn(){
console.log("点击了");
// 点击一次执行过后就解绑
box.removeEventListener('click',fn)
// 在低版本ie中 - detachEvent(on事件类型,函数)
//box.detachEvent('onclick',fn)
}
// box.addEventListener('click',fn)
// 如果使用事件侦听器绑定的事件,就需要用
// removeEventListener(事件类型,要解绑的函数)来解绑
box.attachEvent('onclick',fn)
- 兼容的解绑事件的函数
function bindEvent(ele,type,fn){
if(ele.addEventListener){
ele.addEventListener(type,fn)
}else{
ele.attachEvent('on'+type,fn)
}
}
function unBind(ele,type,fn){
if(ele.removeEventListener){
ele.removeEventListener(type,fn)
}else{
ele.detachEvent('on'+type,fn)
}
}
function fn(){
console.log(123);
// 解绑
unBind(box,'click',fn)
}
bindEvent(box,'click',fn)