[英]How to get ID of an element at a particular coordinate by javascript
考慮在空白瀏覽器頁面上有一個以像素為坐標(2,2)的DIV和一個按鈕。如果我單擊該按鈕,則必須將坐標(2,2)發送給函數,該函數將檢測(2, 2)是否為DIV,BUTTON等,並返回其ID。
這是我嘗試的:
<!DOCTYPE html>
<html lang="en">
<head>
<title>elementFromPoint example</title>
<script>
function changeColor(newColor) {
//To get element from coordinate 2,2
var elem = document.elementFromPoint(2, 2);
//Here i wanted to print what i am getting in var elem
document.getElementById("status").innerHTML = elem;
//next line changes color whatever is at 2,2
elem.style.color = newColor;
//But i want to know whats at 2,2 or get its ID or class.
}
</script>
</head>
<body>
<p id="para1">Some text here</p> <button onclick="changeColor('blue');">blue</button> <span id="status"></span> </body>
</html>
但是通過這種方法,我只能更改其顏色,但是我堅持如何獲取其ID或TYPE(div / button / para / etc)。
var elem = document.elementFromPoint(2, 2);
給您元素引用, id
是該元素的屬性
嘗試
console.log(elem.id);
用於類型
console.log(elem.tagName);
要更新您的狀態,例如:
document.getElementById("status").innerHTML = 'ID:' +elem.id +' , Tag:' +elem.tagName;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.