从 JS 中的 onclick 事件获取 VW/VH 位置

Get VW/VH position from onclick event in JS

此代码将以像素为单位提供点击的 x 和 y 值:

document.getElementById("game").addEventListener("click", function(event) {
   console.log(event.clientX, event.clientY);
});

但是我如何获得与 VH(视口高度)和 VW(视口宽度)相比较的 X 和 Y 值(我想获得的值就像在 CSS 中您可以将元素设置为20vh [视口高度的 20%] 等)

你的意思是这样的吗?

您只需从 window 元素中获取 innerWidthinnerHeight,然后使用 叉积 [= 计算百分比17=]

(elementX * 100) / viewport width
(elementY * 100) / viewport heght

document.getElementById("game")
  .addEventListener("click", function(event) {
    const debug = document.getElementById('debug');
    const clickX = event.clientX;
    const clickY = event.clientY;
      
    const vh = window.innerHeight;
    const vw = window.innerWidth;
  
    const ratioX = (clickX * 100) / vw;
    const ratioY = (clickY * 100) / vh;
  
    debug.innerHTML = '';
    debug.append(`X:${clickX}  Y:${clickY}`);
    debug.append("\n");
    debug.append(`%X:${ratioX} %Y:${ratioY}`);

  });
body {
  background-color: lemon;
  display: flex;
  width: 100vw;
  height: 100vh;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}

#game {
  background-color: cyan;
  width: 29.7vw;
  height: 21vh;
  box-shadow: 0px 0px 2px rgba(0,0,0,.6), 0px 0px 6px rgba(0,0,0,.3);
}
<div id=game></div>

<pre id=debug>
  X:   Y:
  %X: %Y: 
</pre>

您首先需要使用 window.innerWidth 获取视口宽度 (vw),使用 window.innerHeight 获取视口高度 (vh)。

然后,将 event.clientX 除以 vw 并乘以 100 以获得百分比值。获得 Y co-ordinates 的逻辑相同,即将 event.clientY 除以 vh 并乘以 100 以获得百分比值。

查看下面我的演示:(点击游戏获得co-ordinates)

let gameEl = document.getElementById("game"),
  eCXinVWEl = document.getElementById("eCXinVW"),
  eCYinVHEl = document.getElementById("eCYinVH");

gameEl.addEventListener("click", function(event) {
  let vw = window.innerWidth,
    vh = window.innerHeight,
    eCXinVW = event.clientX / vw * 100, // Multiplying by 100 to get percentage 
    eCYinVH = event.clientY / vh * 100; // Multiplying by 100 to get percentage 

  console.log(eCXinVW, eCYinVH);

  eCXinVWEl.innerHTML = eCXinVW;
  eCYinVHEl.innerHTML = eCYinVH;
});
.box {
  padding: 50px;
}

#game {
  padding: 20px;
  background: red;
}
<html>

  <head>
  </head>

  <body>
    <div class="box">
      <h6>Event co-ordinates X by viewport width: <span id="eCXinVW">0</span>%</h6>
      <h6>Event co-ordinates Y by viewport height: <span id="eCYinVH">0</span>%</h6>

      <div id="game">Game</div>
    </div>
  </body>

</html>