Javascript/jquery, get all divs location at (x,y). Forwarding touches? [duplicate]

孤街浪徒 提交于 2020-01-12 07:42:06

问题


Possible Duplicate:
How to get a list of all elements that resides at the clicked point?

I know I can get the element with the highest z-index by using document.elementFromPoint(x,y).

The problem is I need to get every div that contains the touch event's location.

How can I propagate touches to elements underneath?

I have seen some hacky solutions that show/hide elements while re-generating the event, or pointer-events style with css, however I cannot use these and they may cause flickering...

The following diagram illustrates what I need to do:

If the purple, green, and blue boxes represent the div elements, and the red dot is the touch location, I need a function that would return "div3, div2, div1".


回答1:


No flickering with this code:

$("body").click(function(e){
    var x = e.pageX, y = e.pageY;
    var res = [];

    var ele = document.elementFromPoint(x,y);
    while(ele && ele.tagName != "BODY" && ele.tagName != "HTML"){
        res.push(ele);
        ele.style.display = "none";
        ele = document.elementFromPoint(x,y);
    }

    for(var i = 0; i < res.length; i++){
        res[i].style.display = "";
    }
    console.log(res);
});​



回答2:


What about doing:

 $(document).click(function(e) { 
    var pageX = e.pageX;
    var pageY = e.pageY;
    $('*').each(function(index) {
        var offset = $(this).offset();
        var left = offset.left;
        var right = offset.right;
        var width = $(this).width();
        var height = $(this).height();
        if(pageX > left && pageX < left + width) {
             if(pageY > top && pageY < top + height) {
                  //Handle the div
             }
        }
    });
});


来源:https://stackoverflow.com/questions/12847775/javascript-jquery-get-all-divs-location-at-x-y-forwarding-touches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!