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

标签 iphone ios ipad uiwebview

UIWebView如何模拟点击事件?我只需要通过页面脚本处理鼠标按下+向上事件。

最佳答案

我不确定这是否可以通过公共(public) API 实现。使用私有(private) API,这是可能的,如此处所述 synthesizing-touch-event-on-iphone .不过,您将无法在应用商店应用中使用它。

另一种可能的方法是使用 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 的 委托(delegate)方法 webViewDidFinishLoad: 来执行 javascript,并在其中调用 [ webview stringByEvaluatingJavaScriptFromString:@"methodName()"];。检查是否有帮助。

关于iphone - 如何在 UIWebView 上模拟点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13336261/

相关文章:

iphone - Lion上Xcode 4.1的奇怪编译错误

iphone - 如何存储所有这些预先创建的数据?

ios - TableView Cell 自定义类型 Text 自身重叠或为空白

html - uiwebview 和 CSS 文本阴影

ios - iOS 9 中的自定义字体问题?

iphone - 使用单个 Info.plist 构建单独的 iPhone 和 iPad 应用程序

ios - AudioKit 为设备编译,而不是为模拟器编译

ios - 设置UIBarButtonItem不更改标题,仅更改样式

IOS——文件和文件夹管理

ios - iPad 应用程序在每次启动时崩溃