JS相关 | 浏览器事件 |例子应用:点击让球在球场运动

一、浏览器事件要点:

三种分配事件处理程序的方式:

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:示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

  <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>

参考自:现代JavaScript教程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值