最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger focus on an element at a given position - Stack Overflow

programmeradmin4浏览0评论

I e to you with an intersting question.

Given position (x,y) in an HTML document, how can you trigger a focus event on an element at that given position.

The problem translates into is there any way to select the element matching a given position?

Sort of like getElementByPosition?

I e to you with an intersting question.

Given position (x,y) in an HTML document, how can you trigger a focus event on an element at that given position.

The problem translates into is there any way to select the element matching a given position?

Sort of like getElementByPosition?

Share Improve this question asked Sep 7, 2011 at 17:36 Andrei ZisuAndrei Zisu 4,3934 gold badges22 silver badges32 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

The easiest option is to use elementFromPoint:

var element = document.elementFromPoint(x, y);
element.focus();

Other than that, you can write your own function. This is what first came to mind - I used it a while back when there was some reason for elementFromPoint not working correctly, I don't remember what exactly. There are likely to be better ways to do it, but I just tried what I thought of first:

var coords = [100, 100],
    elems = document.getElementsByTagName("*");
for(var i = 0; i < elems.length; i++) {
    var left = elems[i].offsetLeft,
        top = elems[i].offsetTop,
        width = elems[i].offsetWidth;
        height = elems[i].offsetHeight;
    if((left <= coords[0]) && (left + width >= coords[0]) && (top <=coords[1]) && (top + height >= coords[1])) {
        elems[i].focus();
    }
}

You can see it working here.

you can use elementFromPoint(x, y)

https://developer.mozilla/en/DOM/document.elementFromPoint

发布评论

评论列表(0)

  1. 暂无评论