事件下
事件传播行为(事件流)
冒泡模式
冒泡模式就是从里到外触发
event.bubbles(只读属性)
console.log(e.bubbles); //当前事件是否冒泡
<body>
<div>
<button>点我</button>
</div>
</body>
</html>
<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>
禁止冒泡
event方法
- stopPropagation
e.stopPropagation() //阻止事件冒泡 常用的方法 有兼容问题
- cancelBubble
//兼容写法 兼容ie8及以下
e.cancelBubble = true //是一个属性
- 兼容写法
e.stopPropagation?e.stopPropagation():e.cancelBubble=true
console.log('button被点击了');
捕获模式
捕获模式就是从外到里
默认行为
某些操作或者html元素拥有一些默认的行为(a标签的默认行为 进行页面跳转 form里面submit行为 图片的拖动行为)
在某些时候外面的默认行为会导致对应的代码执行出现问题,此时就需要禁止默认行为
禁止默认行为
event 方法
- preventDefault
//大部分浏览器兼容
e.preventDefault()
- 兼容ie低版本写法 returnValue
//兼容ie
e.returnValue = false
- 兼容写法
e.preventDefault ? e.preventDefault() : e.returnValue = false
- return false
return false
事件监听器
- addEventListener 添加事件监听器(可以添加多个多个处理函数)
- removeEventListener移除事件监听器(只能删除由事件监听器添加的 移除根据对应的处理函数是否为一个)
var btn = document.querySelector('button')
var handler = function() {
console.log('点击了');
}
var handler1 = function() {
console.log('点击了1');
}
//属性赋值的方式下面的会覆盖上面的
// btn.onclick = handler
// btn.onclick = handler1
btn.onclick = '' //可以移出对应时间
//btn.removeAttribute('onclick')
//事件监听器 可以有多个处理函数(函数执行不会被覆盖)
//监听对应的时间来执行对应的处理函数
//传入事件名,传入处理函数(如果是匿名函数 就不会被移除)
btn.addEventListener('click', function() {
console.log('点击了按钮');
})
btn.addEventListener('click', function() {
console.log('点击了按钮1');
})
拖拽
基础三大事件
- 鼠标按下事件
- 鼠标移动事件
- 鼠标弹起事件
在页面进行拖拽
var div = document.querySelector('div')
document.onmousedown = function(e) {
e = e || window.event
//鼠标在盒子里面的位置(基于触发元素的偏移位置)
var x = e.offsetX
var y = e.offsetY
document.onmousemove = function(e) {
//获取鼠标在页面里面的位置-对应的按下时鼠标在盒子里面的位置
div.style.left = e.pageX - x + 'px'
div.style.top = e.pageY - y + 'px'
}
document.onmouseup = function() {
document.onmouseup = document.onmousemove = null
}
}
在区间进行拖拽
offset家族
offsetParent 偏移父元素 找离最近的定位元素 如果没有就找body
offsetHeight 偏移元素的高度
offsetWidth 偏移元素的宽度
offsetLeft 离定位父元素偏移的左边的距离
offsetTop 离定位父元素偏移的上边的距离
样式获取
style样式获取只能获取内嵌的样式,也就是只能获取style属性里面的内容
getComputedStyle方法可以获取所有属性