案例:获取鼠标在盒子内的坐标 您所在的位置:网站首页 vue获取鼠标当前坐标 案例:获取鼠标在盒子内的坐标

案例:获取鼠标在盒子内的坐标

2024-07-14 20:07| 来源: 网络整理| 查看: 265

案例:获取鼠标在盒子内的坐标

需求: 我们在盒子内移动鼠标,想要得到鼠标距离盒子左右的距离。 在这里插入图片描述

案例分析:

① 我们在盒子内点击,想要得到鼠标距离盒子左右的距离。

② 首先得到鼠标在页面中的坐标(e.pageX, e.pageY)。

③ 其次得到盒子在页面中的距离 ( box.offsetLeft, box.offsetTop)。

④ 用鼠标距离页面的坐标减去盒子在页面中的距离,得到鼠标在盒子内的坐标。

⑤ 如果想要移动一下鼠标,就要获取最新的坐标,使用鼠标移动事件 mousemove。

代码:

DOCTYPE html> 案例:计算鼠标在盒子内的坐标 .box { width: 300px; height: 300px; background-color: pink; margin: 200px; } var box = document.querySelector('.box'); box.addEventListener('mousemove', function (e) { var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; this.innerHTML = 'x的坐标是' + x + ' y的坐标是' + y; });


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有