2016-11-23 17 views

回答

0

你可以通过找到职位getBoundingClientRect。这是通过使用碰撞检测。如果您不想通过拖动光标执行某些操作,请改为使用drag and drop API

function findElementBehindCursor(cursor, elements) { 
 
    var cursorBoundingBox = cursor.getBoundingClientRect(), 
 
    overlapped; 
 
    overlapped = [...elements].filter(e => isInside(e.getBoundingClientRect(), cursorBoundingBox)); 
 
    return overlapped; 
 
} 
 

 
function isInside(eBounds, cBounds) { 
 
    return eBounds.top < cBounds.top && eBounds.right > cBounds.right && eBounds.bottom > cBounds.bottom && eBounds.left < cBounds.left; 
 
} 
 

 
function runExample() { 
 
    var cursorEle = document.getElementById('draghandle'); 
 
    var liElements = document.getElementById('boxlist').children; 
 
    var results = findElementBehindCursor(cursorEle, liElements); 
 

 
    results.forEach(e => e.style.backgroundColor = 'green'); 
 
}
#wrapper { 
 
    position: relative; 
 
} 
 
#boxlist li { 
 
    width: 200px; 
 
    height: 200px; 
 
    background: red; 
 
    list-style: none; 
 
    margin: 2px; 
 
} 
 
#draghandle { 
 
    width: 10px; 
 
    height: 10px; 
 
    position: absolute; 
 
    top: 100px; 
 
    left: 100px; 
 
    background: yellow; 
 
    border: 1px solid white; 
 
} 
 
button { 
 
    background: blue; 
 
    color: #fff; 
 
}
<button onclick="runExample()">Click to find element behind yellow cursor</button> 
 
<div id="wrapper"> 
 
    <ul id="boxlist"> 
 
    <li></li> 
 
    <li></li> 
 
    <li></li> 
 
    </ul> 
 
    <div id="draghandle"> 
 
    </div> 
 
</div>