我尝试将光标插入页面加载时表单的第一个input
(或上一页的onclick
)。
基本上,我的主页上有一个“立即询问”的链接,我需要它点击进入联系页面,向下滚动到我的 anchor ,然后在第一个元素上 focus()
的形式。我已经尝试过 document.getElementById('____').focus();
但它仅在您已经在页面上时才有效。
这是我在主页上的按钮:
<a href="/contact-us#contact"><button class="cta purple">Enquire Now</button></a>
这是我在联系页面上的输入:
<span class="wpcf7-form-control-wrap your-name"><input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" id="first" aria-required="true" aria-invalid="false" placeholder="Name"></span>
这是否可能内联,例如类似于 document.getElementById('____').focus();
但对于新页面?或者 jQuery“页面加载”解决方案是唯一的选择吗?
最佳答案
- 最简单的方法是将 HTML 与 autofocus attribute 一起使用
<input type="text" name="your-name" autofocus>
- 或者如果您想专注于 javascript (jquery)
$( document ).ready(function() {
$('#first').focus();
});
- 普通 JavaScript
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#first').focus();
});
关于javascript - 自动聚焦于联系表 7 的首次输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54925810/