在IE9中为initMouseEvent()设置pageX

时间:2014-01-08 15:58:56

标签: javascript internet-explorer-9 mouseevent mousemove

我正在编写一个模拟dragAndDrop动作的JS方法。这是为了测试一个基本上是滑块的插件。模拟操作适用于我想要测试的每个浏览器,IE9除外。

这是方法

function dragandDrop(id, className, clientX, clientY, distance){
    var mousedown = document.createEvent("MouseEvent"),
        mouseup   = document.createEvent("MouseEvent"),
        elem      = document.getElementById(id),
        result    = [],
        elems     = elem.getElementsByTagName("*"),
        k         = 0,
        i,
        interval;

    for(i in elems){
        if ((" "+elems[i].className+" ").indexOf(" " + className + " ")>-1){
            result.push(elems[i]);
        }
    }

    mousedown.initMouseEvent("mousedown", true, true, window, 0, 0, 0, clientX, clientY, 0, 0, 0, 0, 0, null);
    result[0].dispatchEvent(mousedown);

    interval=setInterval(function(){
        k++;
        iter(k);
        if(k===distance){
            clearInterval(interval);
            mouseup.initMouseEvent("mouseup", true, true, window, 0, clientX+k, clientY, 220+k, 400, 0, 0, 0, 0, 0, null);
            result[0].dispatchEvent(mouseup);
        }
    },100);

    function iter(y){
        var mousemove=document.createEvent("MouseEvent");
        mousemove.initMouseEvent("mousemove", true, true, window, 0, clientX+y, clientY, clientX+y, clientY, 0, 0, 0, 0, 0, null);
        result[0].dispatchEvent(mousemove);
    }
}

问题是在IE9 initMouseEvent()中没有设置pageX / Y值,这些值是只读的。它们可能总是等于clientX / Y值。该插件使用pageX / Y,所以我需要设置它们以使测试在IE9中工作。

我认为jQuery已经解决了这个问题,但我无法在源代码中找到它。这是我的头脑。但至少可以做到。

我只是不知道如何。

1 个答案:

答案 0 :(得分:0)

我通过添加jQuery解决了这个问题,有时很难看到最明显的答案......

(function(selector, pageX, pageY, distance){
    var $elem     = $(selector),
        k         = 0,interval,
        mousemove = $.Event("mousemove"),
        mousedown = $.Event("mousedown");
        mouseup   = $.Event("mouseup");

    mousedown.pageX = pageX;
    mousedown.pageY = pageY;
    $elem.trigger(mousedown);

    interval = setInterval(function(){
        k++;
        moveMouse(k);
        if(k === distance){
            clearInterval(interval);
            mouseup.pageX = pageX + k;
            mouseup.pageY = pageY + k;
            mouseup.screenX = pageX + k;
            mouseup.screenY = pageY + k;
            $elem.trigger(mouseup);}
        },100);

        function moveMouse(i){
        mousemove.pageX = pageX + i;
        mousemove.pageY = pageY;

        $elem.trigger(mousemove);}

    })(selector, offsetX, offsetY, x);