原生JS,webAPI,案例:计算鼠标在盒子内的坐标

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


<body>
    <div class="box"></div>
    <script>
        // 我们在盒子内点击, 想要得到鼠标距离盒子左右的距离。
        // 首先得到鼠标在页面中的坐标( e.pageX, e.pageY)
        // 其次得到盒子在页面中的距离(box.offsetLeft, box.offsetTop)
        // 用鼠标距离页面的坐标减去盒子在页面中的距离, 得到 鼠标在盒子内的坐标

        var box = document.querySelector('.box');
        box.addEventListener('mousemove', function(e) { // e就是事件对象,可以记录事件发生的时候的环境信息
            // console.log(e.pageX);
            // console.log(e.pageY);
            // console.log(box.offsetLeft);
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            this.innerHTML = 'x坐标是' + x + ' y坐标是' + y;
        })
    </script>

 


版权声明:本文为weixin_44876092原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。