简体   繁体   中英

Get element within clicked pixel?

I'm not sure where to start on this, I've already Googled for a few days trying to find out how to get the element that is within a selected/clicked pixel on the page. I came across this function from a co-worker but I have no idea what it does:

function onclick(e){ 
    var x = e.clientX, 
        y = e.clientY; 

    $("*").filter(function(){ 
        position.left > x && position.left + width < x;
         /*same for height*/;
    }); 
}

Put simply, I need to be able to click a pixel and get the div/element that is within that pixel. It's not as simple for my app as just saying div .class for example because elements overlap one another with opacity and z-index. 在此处输入图片说明

Clicking wherever in the document will log the clicked element.

 $(document).click(function(e) { console.log(e.target); }); 
 .box { width: 50px; height: 50px; background: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='box'></div> 

You could use document.elementFromPoint(x, y); if you want to get an element by x and y coords. See here for docs.

function onclick(e){ 
    var x = e.clientX, 
        y = e.clientY,
        el = document.elementFromPoint(x, y);
}

Fiddle here

The code as shown in the question won't work because variables position , width are not defined, however its basic idea is correct — loop through all the elements and compare the coordinates of a click to each element's box.

Wanted to try it myself. Moved the working demo here instead of a snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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