页面加载或弹窗打开时Elementor搜索表单自动聚焦实现咨询
Elementor搜索表单自动聚焦实现方案
场景1:弹窗内搜索框自动聚焦
可通过监听Elementor官方提供的弹窗打开事件实现,代码可添加至WordPress后台「Elementor - 自定义代码」模块,选择在页脚位置加载即可:
document.addEventListener('elementor/popup/show', () => { // 延时执行确保弹窗内DOM渲染完成 setTimeout(() => { // 可替换为你自定义的搜索框类名 const searchInput = document.querySelector('.elementor-search-form__input'); searchInput && searchInput.focus(); }, 50); });
如果站点存在多个弹窗,可添加弹窗ID判断逻辑,仅在目标搜索弹窗打开时执行:把event.detail.id === 你的搜索弹窗数字ID作为判断条件即可。
场景2:新页面搜索框自动聚焦
有两种实现方案可选:
- 方案1:直接在搜索input标签的属性中添加
autofocus参数,无需额外代码 - 方案2:添加全局JS代码,页面加载完成后自动触发聚焦
window.addEventListener('load', () => { const searchInput = document.querySelector('.elementor-search-form__input'); searchInput && searchInput.focus(); });
内容的提问来源于stack exchange,提问作者JazzSML
相关产品推荐
相关产品推荐

