javascript - 使用 JavaScript 设置 'autofocus' 属性不起作用

标签 javascript html

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

HTML:

<input type="text">

JS:

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

不做:

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

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

最佳答案

尝试这样的事情

document.querySelector('input').focus()

编辑

如果你想要 HTML 5 标准,你应该让 HTML 看起来像这样

<input type="text" autofocus>

http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#autofocusing-a-form-control:-the-autofocus-attribute

关于javascript - 使用 JavaScript 设置 'autofocus' 属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16794394/

相关文章:

javascript - React/TypeScript - 类型 'false | Element' 不可分配给类型 'Element'

javascript - 如何使用 'overwritePermissions' 函数打开某个 channel 的权限?

javascript - 如何捕获浏览器窗口关闭事件?

html - A标签有高度但无法点击

Javascript - 在字段中添加行和总和值

javascript - 如何检测通过 Canvas 生成的图像是否为空白(透明 PNG)?

html - 网站在 Firefox 中运行良好,但在 Chrome 中运行不正常

javascript - 如何通过控制台记录整个 HTML 表单?

javascript - 如何将vue js数据传递给php变量

html - 调整 css 图像大小以适合