elementFromPoint returns null when it used in onscroll event

删除回忆录丶 提交于 2019-12-22 06:59:29

问题


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

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