How to preselect contenteditable field in UIWebView iOS5

烈酒焚心 提交于 2019-11-29 04:50:16
sciritai

Unfortunately you can't do that in Mobile Safari. I believe Apple chose to restrict this from happening because when you visit some sites, like Google for example, the search field gets focused immediately. This would be extremely annoying for users if every site they went to, the keyboard popped up. On Desktop this behaviour doesn't matter but on mobile devices it's very noticeable.

Related: Mobile Safari Autofocus text field

Now if anyone wants to achieve this in iOS 6, he can open iOS keyboard programmatically like this,

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    // keyboardDisplayRequiresUserAction available in iOS >= 6 
    if ([webView respondsToSelector:@selector(setKeyboardDisplayRequiresUserAction:)]) {
        webView.keyboardDisplayRequiresUserAction = NO;
    }
}

and then,

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // Assuming that you're using jquery. If not, use document.getElementById('YourInputElementID')
    NSString *evalStr = [NSString stringWithFormat:@"setTimeout( function(){$('#YourInputElementID').focus();},1000);"];
    [webView stringByEvaluatingJavaScriptFromString:evalStr];
}

This will run this javascript after 1sec. For safe side you should call the get focus code when the focusing element has been loaded.

You can summon the keyboard if you are in the context of a click event handler.

For example

document.body.addEventListener('click', function() {
  content.focus();
}, false);

should work

I have no info about contenteditable on iOS but I think that you should be able to simply create a range and add it to the selection.

var input; // your contenteditable element
var range = document.createRange();
range.selectNodeContents(input);

var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!