问题
I have a simple html page with a master div with fixed height (scrollable) and 2 small divs in this div. I am trying to get the current element in the middle point of master div during scroll. It works good on all browsers except IE8. In IE8, document.elementFromPoint() returns null in onscroll event for all possible values as coordinates. Anyone knows a workaround or solution for this problem?
Here is HTML code:
<div id="mainDiv" style="height:300px;min-height:300px;overflow:auto;" onscroll="mouseScrolled();">
<div id="div1" style="height:500px;min-height:500px;background-color:blue;display:block;">
</div>
<div id="div2" style="height:500px;min-height:500px;background-color:red;display:block;">
</div>
</div>
<span id="debugSpan">
</span>
javascript:
function mouseScrolled(event) {
var mainDiv = document.getElementById('mainDiv');
var x = getXY(mainDiv)[0] + mainDiv.offsetWidth / 2;
var y = getXY(mainDiv)[1] + mainDiv.offsetHeight / 2;
var ctr = document.elementFromPoint(x , y);
document.getElementById('debugSpan').innerHTML = "ClientX=" + x + "<BR>" + "ClientY=" + y +"<BR> Control:" + ctrId;
}
function getXY(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
while (obj = obj.offsetParent)
}
return { x: curleft, y: curtop };
}
回答1:
While perhaps not the most elegant of solutions, I ended up checking if I received something from elementFromPoint and if not, use a setTimeout(fn, 0) to retry the function call at the next free clock cycle. In IE9 and other browsers, it seems to work the first time; for IE8, it sets the timeout and fires after the scroll event processing is done, which gives an element.
来源:https://stackoverflow.com/questions/8227345/elementfrompoint-returns-null-when-it-used-in-onscroll-event