javascript - 如何将 offsetX 和 offsetY 坐标从像素更改为百分比?

标签 javascript html css vue.js

我正在开发一个工具,我希望在将鼠标悬停在 div 元素上时以百分比 (%) 格式显示 offsetX 和 offsetY 坐标。默认情况下,它采用像素格式。

index.html 文件:

 <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title>Events</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <link rel="stylesheet" href="style/style.css">
      </head>
      <body>
        <div id="vue-events">
          <h1>Events in VueJS</h1>
          <div id="canvas" v-on:mousemove="updateXY">
            <img src="img/img-1.jpg" style="visibility: hidden;" />
              {{x}}, {{y}}
          </div>
        </div>
       <script src="js/events.js"></script>
      </body>
    </html>

event.js 文件:

new Vue({
      el: '#vue-events',
      methods:{
        updateXY: function(event){
           this.x = event.offsetX;
           this.y = event.offsetY;
        }
      }
    });

最佳答案

你得自己算算

你得到了窗口的宽度和高度,并以此为基础你可以计算出百分比。但请记住,如果您调整窗口大小,该值可能会有所不同。

   new Vue({
      el: '#vue-events',
      methods:{
        updateXY: function(event){
           this.x = (event.offsetX * 100) / window.innerWidth;
           this.y = (event.offsetY * 100) / window.innerHeight;
        }
      }
    });

关于javascript - 如何将 offsetX 和 offsetY 坐标从像素更改为百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58299967/

相关文章:

javascript - 如果它是 jquery 中的超链接,则获取 td 的值

javascript - 在不滚动的情况下单击到另一页后返回上一节

html - 堆叠文本与网页横幅中的 Logo 对接

html - 将 div 与位置相对水平对齐

如果长于页面宽度,asp.net 菜单控件隐藏元素

javascript - 当我只能将 "attach"函数传递给构造函数时,为什么要使用原型(prototype)?

javascript - Chart.js - 更改 x 轴时间序列的刻度/标签位置

html - Facebook 时间线宽度不会改变

android - Google Web Fonts 不适用于 Android 4.2.2 高棉语

javascript – 如何在 100vh 滚动后淡出一个类?