使用JavaScript设置'autofocus'属性不起作用 [英] Setting 'autofocus' attribute with JavaScript not working

查看:1737
本文介绍了使用JavaScript设置'autofocus'属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小插件,插件将封装自动对焦设置,但是当我使用JavaScript动态添加属性时,它不会自动对焦页面,这很奇怪。反正有吗?

I am writing a small plugin, and the plugin will encapsulate an autofocus setting, but when I add the attribute dynamically with JavaScript, it doesn't autofocus the page, which is weird. Is there anyway around this?

HTML:

<input type="text">

JS:

document.querySelector('input').setAttribute('autofocus', 'autofocus');

不做:

document.querySelector('input').setAttribute('autofocus', 'autofocus').focus();

jSFiddle: http://jsfiddle.net/wPUNN/

jSFiddle: http://jsfiddle.net/wPUNN/

推荐答案

最好的方法似乎是:

document.querySelector('input').autofocus = true;

这篇文章可能有助于解释为什么要使用反射属性:https://stackoverflow.com/a/18770417/3920924

This post might help explain why to use a reflected property: https://stackoverflow.com/a/18770417/3920924

但似乎您需要申请它靠近文档加载。否则它似乎没有发射。我想那是因为这里( http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#autofocusing-a-form-control:- -autofocus-attribute:the-dialog-element )它被定义为在加载页面后立即工作。我没有看到任何其他说它可以在以后调用的东西。每次我试图以类似setTimeout 3秒的时间点击它时,它从不关注该字段。

However it seems you need to apply it near the document load. Otherwise it doesn't seem to fire. I think that's because here (http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#autofocusing-a-form-control:-the-autofocus-attribute:the-dialog-element) it's defined to work as soon as the page is loaded. I haven't seen anything else that says it can be called later in time. Every time I've tried to fire it later with like a setTimeout of 3 seconds it never focuses the field.

这篇关于使用JavaScript设置'autofocus'属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆