admin管理员组文章数量:1430460
I'm trying to use the javascript function focus()
, but it does not work on safari mobile. How do I fix this problem?
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<script type="text/javascript">
window.onload=function() {
document.getElementById('username').focus();
}
</script>
</head>
<body>
<input type="text" id="username" >
<input type="text" >
</body>
</html>
I'm trying to use the javascript function focus()
, but it does not work on safari mobile. How do I fix this problem?
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<script type="text/javascript">
window.onload=function() {
document.getElementById('username').focus();
}
</script>
</head>
<body>
<input type="text" id="username" >
<input type="text" >
</body>
</html>
Share
Improve this question
edited Jan 14, 2016 at 8:59
Dmitriy
5,56512 gold badges27 silver badges39 bronze badges
asked Jan 14, 2016 at 8:11
VagorVagor
211 silver badge2 bronze badges
2 Answers
Reset to default 4iOS does not allow .focus()
to be fired automatically for security reason.
I was having the same problem with an Angular app, and I solved it with a very simple hack.
For starters, you might want to use jQuery; it makes a lot of things clear-cut for you and is more-or-less fully supported. Then, try doing this:
$( document ).ready( function() {
setTimeout( $( '#username' ).focus(), 0 );
});
Now, I don't exactly know how it works; maybe some rendering issue. But it works for sure.
If you want VanillaJS:
window.onload = function() {
setTimeout( document
.getElementById( 'username' ).focus(), 0 );
}
I don't know if the VanillaJS version will work.
本文标签: javascriptwhy iOS mobile cannot use focus()Stack Overflow
版权声明:本文标题:javascript - why iOS mobile cannot use focus() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745558876a2663351.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论