[英]Get X,Y position of element in Javascript
我想找到相對於 SVG 元素的鼠標單擊的 X,Y position。 SVG 元素將嵌入 HTML 中。
var svg = document.getElementById("svg1"); svg.addEventListener('click', event => { let x = event.clientX; let y = event.clientY; console.log(x, y); });
html { height: 100% } body { height: 100%; display: flex; justify-content: center; background-color: #fff; } svg { height: 100%; background: grey; }
<svg id="svg1" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="#52c927" /> <circle cx="50" cy="50" r="25" fill="white" /> <circle cx="50" cy="50" r="15" fill="red" /> </svg>
想要在控制台打印 X 和 Y 之前減去 SVG 的 offsetLeft 和 offsetTop。 但無法獲得那些價值
要獲取元素坐標或大小,請使用Element.getBoundingClientRect
event.target.getBoundingClientRect()
或event.currentTarget.getBoundingClientRect()
(用於綁定到偵聽器的元素,而不是傳播事件的元素)。 或者直接使用緩存的元素引用常量svg.getBoundingClientRect()
const bcr = event.target.getBoundingClientRect();
console.log(bcr.left, bcr.top)
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
在您的特定情況下,要獲取相對鼠標坐標:
var svg = document.getElementById("svg1");
svg.addEventListener('click', event => {
const bcr = event.target.getBoundingClientRect();
const relative_x = event.clientX - bcr.left;
const relative_y = event.clientY - bcr.top;
console.log(relative_x, relative_y);
});
您可以像這樣獲取相對於元素的坐標:
var svg = document.getElementById("svg1"); svg.addEventListener('click', event => { const rect = svg.getBoundingClientRect(); let x = event.clientX - rect.left; let y = event.clientY - rect.top; console.log(x, y); });
html { height: 100% } body { height: 100%; display: flex; justify-content: center; background-color: #fff; } svg { height: 100%; background: grey; }
<svg id="svg1" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="#52c927" /> <circle cx="50" cy="50" r="25" fill="white" /> <circle cx="50" cy="50" r="15" fill="red" /> </svg>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.