elementFromPoint在onscroll事件中使用时返回null [英] elementFromPoint returns null when it used in onscroll event

查看:301
本文介绍了elementFromPoint在onscroll事件中使用时返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的html页面,其中包含一个固定高度(可滚动)的主div和此div中的2个小div。我想在滚动期间将当前元素放在master div的中间点。它适用于除IE8以外的所有浏览器。在IE8中,document.elementFromPoint()在onscroll事件中返回null,将所有可能的值作为坐标。有人知道这个问题的解决方法或解决方案吗?

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?

这是HTML代码:

<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:

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


推荐答案

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

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.

这篇关于elementFromPoint在onscroll事件中使用时返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆