5

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 };
    }
4

1 回答 1

3

虽然可能不是最优雅的解决方案,但我最终检查了是否从 elementFromPoint 收到了某些内容,如果没有,则使用 setTimeout(fn, 0) 在下一个空闲时钟周期重试函数调用。在IE9等浏览器中,似乎是第一次工作;对于 IE8,它设置超时并在滚动事件处理完成后触发,这会给出一个元素。

于 2012-01-10T21:24:09.180 回答