事件的传播行为(事件流)
冒泡模式(默认模式)
冒泡模式就是从里到外触发
event.bubbles(只读属性)
console.log(e.bubbles)//当前事件是否冒泡
<div>
<button>点我</button>
</div>
<script>
//点击按钮 先触发按钮的点击事件 然后触发div的点击事件 然后触发document的点击事件
document.onclick = function(){
console.log('文档被点击了');
}
document.querySelector('div').onclick = function(){
console.log('div被点击了');
}
document.querySelector('button').onclick = function(e){
console.log(e.bubbles);//当前事件是否冒泡
console.log('button被点击了');
}
</script>
阻止事件冒泡
stopPropagation()方法 有兼容问题,阻止事件冒泡的常用方法
兼容方法
cancelBubble(属性)
兼容写法
e.stopPropagation()?e.stopPropagation():e.cancelBubble=true
捕获模式
捕获魔兽就是从外到里触发
默认行为
某些操作或者html元素拥有一些默认的行为(a标签的默认行为,form里面submit行为 图片拖拽的动作)
在某些时候外面的某人行为会导致对应的代码执行出现问,这时候就需要禁止默认行为
preventDefault(方法)阻止默认行为,大部分浏览器兼容
兼容 returnValue 属性
e.returnValue = false 兼容ie
兼容写法e.preventDefault?e.preventDefault():e.returnValue = false
事件监听(兼容问题)
addEventListener 添加事件监听器(可以添加多个处理函数)
removeEventListenner移出事件监听器(只能移出addEventListener添加的,根据对应的处理函数 是不是一个) 函数是一个引用类型,如果用匿名函数的话,获取不到同一个函数 那么就无法清除
//我需要俩个处理函数 事件监听器 可以有多个处理函数
//监听对应的事件执行 来执行对应的处理函数 (不会覆盖之前的事件的处理函数)
//传入事件名 传入处理函数 (如果是直接传入function 就不会被移除)
btn.addEventListener('click',function(){
console.log('点击了按钮');
})
btn.addEventListener('click',function fn(){
console.log('点击了按钮1');
})
btn.addEventListener('click',handler1)
//移除事件监听器 必须处理函数是同一个 不然不能被移除 只能移除addEventListener添加的
btn.removeEventListener('click',function fn(){
console.log('点击了按钮1');
})//不能移除
btn.removeEventListener('click',handler1) //能
btn.removeEventListener('click',handler)//不能移除
拖拽
基础三大事件
1.鼠标按下事件(mousedown)
2.鼠标移动事件(mousemove)
3.鼠标弹起事件(mouseup)
在页面进行拖拽
offset家族(属性 元素对象)
offsetParent 偏移父元素(找离最近的定位父元素,如果没有定位就找body)
offsetHeight 偏移元素高度
offsetWidth偏于元素的宽度
offsetLeft离父元素偏移的左边的距离(number类型)
offsetTop离父元素偏移的上边距离(number类型)
样式获取
style属性 只能获取内嵌样式
var div = document.getElementsByTagName('div')[0]
//style的弊端 他只能获取对应的内嵌的样式 也就是只能获取style属性里面写的内容
console.log(div.style.width); //空字符串
console.log(div.style.height); //300px
getComputsdStyle方法可以获取所有的样式
//对应的兼容获取所有样式的方法
var style = getComputedStyle(div, '')
console.log(style); //getComputedStyle获取样式对象里面都有默认值(所有的样式)
console.log(style.backgroundColor);
console.log(style.color);
console.log(style.width);
console.log(style.height);
currentSyle ie的低版本兼容
console.log(div.currentStyle); //ie低版本兼容 废弃
兼容封装
// getComputedStyle 兼容问题
// console.log(div.currentStyle); //ie低版本兼容 废弃
//兼容写法 传入一个元素 返回一个样式对象
function getStyle(element) {
var style = window.getComputedStyle ? getComputedStyle(element, '') :
element.currentStyle
return style