繁体   English   中英

如何通过javascript获取特定坐标处元素的ID

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM