一、浏览器事件要点:
三种分配事件处理程序的方式:
1.HTML 特性(attribute):οnclick="…"。(很少使用)
2.DOM 属性(property):elem.onclick = function。(无法为特定事件分配多个处理程序)
3.方法(method):elem.addEventListener(event, handler[, phase]) 用于添加,removeEventListener 用于移除。(是最灵活的,但也是写起来最长的。有少数事件只能使用这种方式。例如 transtionend 和 DOMContentLoaded。addEventListener 也支持对象作为事件处理程序。)
对于文档级的处理程序 —— 始终使用的是 addEventListener
二、例子
1.让球在球场运动
点击球场中任意一点,让球在球场中移动:
html:
草地field和球ball
<body style="height:2000px">
<div id="field">
<img src="https://en.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div>
</body>
css:
1让球相对于草地定位,position是子绝(ball,position:absolute)父相(field,position:relative)
2.field的overflow属性设置为hidden(溢出隐藏)
3.ball设置一个transition过渡,使球从一个位置运动到另一个位置的时间为1s,而不是直接闪现!
<style>
#field {
width: 200px;
height: 150px;
border: 10px solid black;
background-color: #00FF00;
position: relative;
overflow: hidden;
cursor: pointer;
}
#ball {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
transition: all 1s;
}
</style>
javascript:
<script>
document.getElementById('field').addEventListener("click",function1);
function function1(event){
let fieldCoords=this.getBoundingClientRect(); //React相关的
let ball=document.getElementById('ball');
let ballCoords={
left:(event.clientX-fieldCoords.left-ball.offsetWidth / 2),
top:(event.clientY-fieldCoords.top-ball.offsetTop / 2)
};
if(ballCoords.left<0) ballCoords.left=0;
if(ballCoords.top<0) ballCoords.top=0;
if(ballCoords.left+ball.clientWidth>field.clientWidth){
ballCoords.top=field.clientWidth-ball.clientWidth;
}
if(ballCoords.top+ball.clientHeight>field.clientHeight){
ballCoords.top=field.clientHeight-ball.clientHeight;
}
ball.style.left=ballCoords.left+'px';
ball.style.top=ballCoords.top+'px';
}
</script>