首页 > 解决方案 > 将图像放在彼此顶部时,CSS/JS Top 和 Left 会变形

问题描述

我有一张篮球场的图像,想在球场上放置一个绿点或红点(如果从该点投篮,则为绿色,如果未命中则为红色)。

篮球投篮通过某人点击球场的图像来记录,然后坐标(以百分比表示)保存到数据库中。完成录制后,在单独的视图中,我调用所有这些坐标并为它们设置以下参数:

var marker = document.createElement("IMG");
marker.src = image;
marker.style.width = '4%';
marker.style.position = 'absolute';
marker.style.left = offsetLeft + "%";
marker.style.top = offsetTop + "%";
shotChartBox.appendChild(marker);

offetLeft 和 Top 都是数据库中的值乘以 100 并给出 % 符号。

但是,当我这样做时,这些点总是会有点偏离。如果有人点击球场图像的死点,该点将出现在稍微上方和右侧。我知道这不是数据捕获问题,因为当我进入浏览器检查工具并手动设置一个点以使顶部和左侧值恰好为 50% 时,同样的事情发生了。

我已经尝试将点本身的 4% 宽度考虑在内,但无法找到一种方法来做到这一点并使其适用于所有浏览器尺寸。当我在这里和那里增加或减少 2% 之后调整浏览器的大小时,它总是把事情弄得更糟。

如果您有任何想法,请告诉我。我觉得好像有一个定位或 JS 的东西我只是不知道。

//A couple example function calls
displayMarker(0.5, 0.5, "https://i.postimg.cc/8CLJ8Wj6/makeIcon.png");
displayMarker(0.25, 0.25, "https://i.postimg.cc/mDRcTDH6/missIcon.png");

function displayMarker(x, y, image) {
  var courtImage = document.getElementById('shotChart');
  var shotChartBox = document.getElementById('shotChartBox');

  var offsetLeft = x * 100;
  var offsetTop = y * 100;

  var marker = document.createElement("IMG");
  marker.src = image;
  marker.style.width = '4%';
  marker.style.position = 'absolute';
  marker.style.left = offsetLeft + "%";
  marker.style.top = offsetTop + "%";
  shotChartBox.appendChild(marker);
}
<h2>Shot Chart</h2>
<div id="shotChartBox">
  <img id="shotChart" src="https://i.postimg.cc/rswKtPg1/shot-Chart.png" width="100%" />
</div>

JSFiddle 演示

标签: javascripthtmlcss

解决方案


假设 0.5,0.5 相当于球场的中心,这里是一个可行的解决方案。

<html>
<style></style>

<body>
  <div id="shotChartBox" style="position: relative;">
    <img style="position: relative" src="https://i.postimg.cc/rswKtPg1/shot-Chart.png" width="100%" height="auto" />
  </div>
  <script>
    displayMarker(0.5, 0.5, "https://i.postimg.cc/8CLJ8Wj6/makeIcon.png");
    displayMarker(0.25, 0.25, "https://i.postimg.cc/mDRcTDH6/missIcon.png");

    function displayMarker(x, y, image) {
      var shotChartBox = document.getElementById("shotChartBox");

      var offsetLeft = x * 100 - 2;
      var offsetTop = y * 100 - 1;

      var marker = document.createElement("IMG");
      marker.src = image;
      marker.style.width = "4%";
      marker.style.position = "absolute";
      marker.style.left = offsetLeft + "%";
      marker.style.top = offsetTop + "%";
      shotChartBox.appendChild(marker);
    }
  </script>
</body>

</html>


推荐阅读