我正在尝试将光标插入页面加载时表单的第一个input中(或上一页的onclick中)。

基本上,我在主页上有一个链接“现在查询”,我需要它单击以进入联系页面,向下滚动到我的锚点,并在表单的第一个元素上输入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/

10-13 09:11