在使用UITextView时,有相关的资源可供使用。我该如何注册Done
键按钮按下事件?当用户聚焦Web视图中的表单时,键盘会显示出来。
onfocusout
的DOM事件(有关详细信息,请参见http://www.w3schools.com/jsref/event_onfocusout.asp)。[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('youTextFieldID').addEventListener('onfocusout', function () {"
@"var frame = document.createElement('iframe');"
@"frame.src = 'doneEditing://';"
@"document.body.appendChild(frame);"
@"setTimeout(function () { document.body.removeChild(frame); }, 0);"
@"}, false);"];
请按照以下方式编写您的UIWebView委托方法:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([request.URL.scheme isEqualToString:@"doneEditing"]) {
// Call you event handler here
[self doneButtonTouchEventHandler]
return NO;
}
return YES;
}
祝你好运
关键在于当网页加载时添加事件监听器。我假设你想了解文本字段的 blur
事件。
这是一个基本的工作示例:
<html>
<head>
<script>
function initPage() {
document.addEventListener('focusin', handleFocusIn);
document.addEventListener('focusout', handleFocusOut);
}
function handleFocusIn(e) {
alert('In');
}
function handleFocusOut(e) {
alert('Out');
}
</script>
</head>
<body onload="initPage()">
<form>
<input type="text" name="username">
</form>
</body>
</html>
@Ducky 这是针对UIWebView的答案
这里提供了WkWebview的解决方案
将ViewController扩展为WKNavigationDelegate
webView.navigationDelegate = self
实现和覆盖函数 获取您的按钮ID并写入document.getElementById 此方法在页面加载完成时调用
func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
print("loaded")
let doneJS = """
document.getElementById('m_ara_input').addEventListener('focusout', function () {
var frame = document.createElement('iframe');
frame.src = 'doneEditing://';
document.body.appendChild(frame);
setTimeout(function () { document.body.removeChild(frame); }, 0);
}, false);
"""
webView.evaluateJavaScript(doneJS, completionHandler: nil)
}
重写下面的方法
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {return}
if (url.scheme == "doneediting") {
executeSubmit()
}
decisionHandler(.allow)
}
func executeSubmit(){
let js = """
var a = document.getElementsByClassName("btn btn-default pull-left");
a.ara_buton.click();
"""
webView.evaluateJavaScript(js, completionHandler: nil)
}
ara_buton
是按钮的"name"属性。