我有一个 anchor 标签,当点击它时,我想要一个输入以获得焦点并且页面滚动到表单。两者都没有发生,我不知道为什么,因为它太简单了。这是 anchor 标记:
<a href="#RSVPForm" title="RSVP Now!" class="button">RSVP Now</a>
这是 JavaScript:
const firstname = document.getElementById("firstname");
const rsvpcta = document.querySelector("a[href*='#RSVPForm']");
rsvpcta.addEventListener("click", () => {firstname.focus();})
它在 Safari 中有效,但在其他浏览器中无效。我不知道为什么它在其他任何地方都不起作用。 我的测试网址是:https://meganandadam2018.com
最佳答案
给 anchor 标签添加onclick事件
<a onclick="focusfunc()">RSVP Now</a>
单击链接时将调用 focusfunc() 函数。并添加 focus() 方法如下:
function focusfunc(){
document.getElementById("firstname").focus();
}
关于JavaScript onclick 处理程序不聚焦或滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49327768/