如何在UIWebView上模拟点击事件?

4
如何在UIWebView上模拟点击事件?我只需要通过页面脚本处理鼠标按下+抬起事件。
1个回答

3

我不确定这是否可以通过公共API实现。使用私有API,如synthesizing-touch-event-on-iphone所述,这是可能的。但你将无法在appstore应用程序中使用此功能。

另一种可能的方法是使用javascript。不确定这是否正是您想要的。可以使用javascript来实现,如here所述,

function simulate(element, eventName)
    {
        var options = extend(defaultOptions, arguments[2] || {});
        var oEvent, eventType = null;

        for (var name in eventMatchers)
        {
            if (eventMatchers[name].test(eventName)) { eventType = name; break; }
        }

        if (!eventType)
            throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

        if (document.createEvent)
        {
            oEvent = document.createEvent(eventType);
            if (eventType == 'HTMLEvents')
            {
                oEvent.initEvent(eventName, options.bubbles, options.cancelable);
            }
            else
            {
                oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
            }
            element.dispatchEvent(oEvent);
        }
        else
        {
            options.clientX = options.pointerX;
            options.clientY = options.pointerY;
            var evt = document.createEventObject();
            oEvent = extend(evt, options);
            element.fireEvent('on' + eventName, oEvent);
        }
        return element;
    }

    function extend(destination, source) {
        for (var property in source)
          destination[property] = source[property];
        return destination;
    }

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}

然后使用,

simulate(document.getElementById("btn"), "click");

您可以通过在您的UIViewController中实现UIWebView的委托方法webViewDidFinishLoad:,并在其中调用[webview stringByEvaluatingJavaScriptFromString:@"methodName()"];来尝试执行JavaScript。请检查是否有帮助。

非常感谢!但是如何使用上次已知的鼠标位置在JavaScript上创建事件?这是可能的吗? - Dmitry
我对JavaScript没有太多经验。如果有帮助的话,可以查看这个链接:http://stackoverflow.com/questions/1222958/javascript-create-event-with-current-mouse-coordinates。如果这不起作用,你可能需要发布一个新问题,因为它是一个不同的问题。 - iDev
它对我没有帮助 - 脚本在我的情况下无法工作:( 第一个链接在SDK6上有18个错误。 - Dmitry
对不起,我应该使用鼠标坐标作为选项来调用它以使其工作。如何做到这一点? - Dmitry
1
就像我说的,我不确定javascript,你有没有查看http://stackoverflow.com/questions/1222958/javascript-create-event-with-current-mouse-coordinates - iDev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接