20200914冯佳丽
学习日志
事件
在js中的动态绑定
一个事件仅绑定一个处理函数
一个事件可绑定多个处理函数
elem.addEventListener("事件名",fn);
elem.removeEventListener("事件名",fn)
案例:导弹追踪系统
有几个按钮:
1、导弹按钮,装载导弹
2、发射按钮
3、卸载按钮
默认情况下,点击发射按钮,只发射普通子弹,当点击导弹按钮之后,会发射导弹,不再发射普通子弹,只有卸载导弹后,才会重新发射普通子弹
<button class="btnShoot">发射</button><br>
<button class="btnAward">导弹</button><br>
<button class="btnBreak">卸载</button><br>
<script type="text/javascript">
var btnShoot=document.querySelector(".btnShoot")
var btnAward=document.querySelector(".btnAward")
var btnBreak=document.querySelector(".btnBreak")
btnShoot.onclick=function(){
console.log("----发射子弹---")
}
function award(){
console.log("----发射导弹---")
}
btnAward.onclick=function(){
btnShoot.onclick=null;
btnShoot.addEventListener("click",award);
}
btnBreak.onclick=function(){
btnShoot.onclick=function(){
console.log("----发射子弹---")
}
btnBreak.removeEventListener("click",award);
}
</script>
事件模型
DOM
3个阶段:
捕获
由外向内, 记录各级父元素绑定的事件处理函数,只记录,不执行
目标触发
优先触发目标元素上的事件处理函数
冒泡
由内向外, 反向依次触发捕获阶段记录的事件处理函数
var d1=document.getElementById("d1")
var d2=document.getElementById("d2")
d1.onclick=function(e){
console.log("我是d1")
// 阻止冒泡事件的发生
// e.stopPropagation()
}
d2.onclick=function(e){
console.log("我是d2")
// 阻止冒泡事件的发生
e.stopPropagation()
}
注:事件委托
e是我们的事件对象,事件对象是我们每个事件事件自带的
e.target指向我们点击的目标元素
- 1
- 2
- 3
<script type="text/javascript">
var list=document.getElementById("list")
list.onclick=function(e){
console.log(e.target)
}
</script>
事件对象:
事件发生时自动创建
封装事件信息的
并提供操作事件的API的对象
操作
取消冒泡/停止蔓延
function(e){
e. stopPropagation();
}
取消事件/阻止默认行为
e.preventDefault()
事件坐标
相对于屏幕左上角 e.screenX/screenY
相对于文档显示区左上角 e.clientX/clientY
相对于触发事件元素的左上角 e.offsetX/offsetY
页面滚动
事件
window.onscroll
获得页面滚动过的高度
document.body.scrollTop
document.documentElement.scrollTop
方法
window.scrollBy(left的增量,top的增量)
window.scrollTo(left,top)
今日感想
多敲多练习吧,慢慢的理解!敲敲敲!
近期评论