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

代码思路:

  1. 我们在盒子内点击,想要得到鼠标距离盒子左右的距离。
  2.     首先得到鼠标在页面中的坐标( e.pagex e.pageY )
  3.     其次得到盒子在页面中的距离( box.offsetLeft, box.offsetTop)
  4.     用鼠标距离页面的坐标减去盒子在页面中的距离,得到鼠标在盒子内的坐标
  5.     如果想要移动一下鼠标,就要获取最新的坐标,使用鼠标移动事件mousemove

效果如下:

html部分:

    <div class="box"></div>

css部分:

    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 100px;
        }
    </style>

javascript部分:

    let box = document.querySelector('.box');
    box.addEventListener('mousemove', function (e) {
        // console.log(e.pageX);
        // console.log(e.pageY);
        // console.log(box.offsetLeft);
        let x = e.pageX - this.offsetLeft;
        let y = e.pageY - this.offsetTop;
        this.innerHTML = `x坐标是:${x},y坐标是:${y}`
    })

猜你喜欢

转载自blog.csdn.net/weixin_45904557/article/details/125380787