zoukankan      html  css  js  c++  java
  • 0187 案例:获取鼠标在盒子内的坐标

    1. 我们在盒子内点击,想要得到鼠标距离盒子左右的距离。
    2. 首先得到鼠标在页面中的坐标(e.pageX, e.pageY)
    3. 其次得到盒子在页面中的距离 ( box.offsetLeft, box.offsetTop)
    4. 用鼠标距离页面的坐标减去盒子在页面中的距离,得到 鼠标在盒子内的坐标
    5. 如果想要移动一下鼠标,就要获取最新的坐标,使用鼠标移动
    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;
    })
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            .box {
                 300px;
                height: 300px;
                background-color: pink;
                margin: 200px;
            }
        </style>
    </head>
    
    <body>
        <div class="box"></div>
        <script>
            // 我们在盒子内点击, 想要得到鼠标距离盒子左右的距离。
            // 首先得到鼠标在页面中的坐标( e.pageX, e.pageY)
            // 其次得到盒子在页面中的距离(box.offsetLeft, box.offsetTop)
            // 用鼠标距离页面的坐标减去盒子在页面中的距离, 得到 鼠标在盒子内的坐标
            var box = document.querySelector('.box');
            box.addEventListener('mousemove', function(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>
    </body>
    
    </html>
    
  • 相关阅读:
    Java修改excel内容
    text标签onchang事件
    shh将数据导出excel
    正则表达式0到200以内的数
    虚拟内存与物理内存
    捕获内核的异常事件
    linux内存(三)内核与用户空间交互
    linux内存(二)高端内存
    linux内存(一) 内核空间与用户空间
    使用tc配置后端设备,来限制虚拟机网卡带宽
  • 原文地址:https://www.cnblogs.com/jianjie/p/12184805.html
Copyright © 2011-2022 走看看