如何使用JavaScript查找内嵌SVG图像的(x,y)坐标

问题描述 投票:0回答:1

我正在编写我的第一个Flask Web应用程序。我有一个显示5x5网格的HTML页面。我具有onClick="clickRC(event)<div>属性,其中包含一个内联<svg>图像。我试图找出用户单击的网格中的行和列。我知道如何从鼠标单击事件((x,y)和包含矩形的((最左边的x,最上面的y))计算它。

但是我无法弄清楚包含的矩形<svg>元素的位置。这是代码:

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"/>
</head>
<body>
<script>
   function clickRC(event) {
      var n = 5;
      var boxsize = 24;
      var elem_svg = document.getElementById("svg5x5");
      var xbase = elem_svg.offsetLeft;
      var ybase = elem_svg.offsetTop;
      var r = Math.floor(1 + ((ybase - event.offsetY) / boxsize));
      var c = Math.floor(1 + ((xbase - event.offsetX) / boxsize));
      alert("DEBUG: xbase=" + xbase + ",ybase=" + ybase + ",r=" + r + ",c=" + c );
      // ... Do something with the computed row and column
   }
</script>
<div id="grid-svg" class="w3-container" onclick="clickRC(event)">
<svg id="svg5x5"
     width="100%"
     height="100%"
     viewbox="0 0 120 120"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     >
<rect fill="white" height="120" stroke="black" stroke-width="2" width="120" />
<line stroke="black" x1="0" x2="0" y1="120" />
<line stroke="black" x1="24" x2="24" y1="120" />
<line stroke="black" x1="48" x2="48" y1="120" />
<line stroke="black" x1="72" x2="72" y1="120" />
<line stroke="black" x1="96" x2="96" y1="120" />
<line stroke="black" x1="0" x2="120" y1="0" y2="0" />
<line stroke="black" x1="0" x2="120" y1="24" y2="24" />
<line stroke="black" x1="0" x2="120" y1="48" y2="48" />
<line stroke="black" x1="0" x2="120" y1="72" y2="72" />
<line stroke="black" x1="0" x2="120" y1="96" y2="96" />
</svg>
</div>
</body>
</head>

我已经尝试过offsetTop以及其他我能想到的东西。我在Chrome中打开页面,并使用内置的[[inspect调试窗口)查看所有属性和属性的列表。没用。访问包含元素的左上(x,y)坐标的正确方法是什么?

javascript python html flask dom
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.