ExpressJS/EJS中Trix编辑器自动聚焦问题修复求助
解决Trix编辑器自动聚焦抢占输入框的问题
问题场景
基于NodeJS/Express搭建的博客,使用Trix编辑器处理文章撰写与编辑时,编辑页面的Trix富文本区域会自动聚焦,导致无法编辑标题等其他文本框。相关EJS代码如下:
<form action="/edit-post/<%= data._id %>?_method=PUT" method="POST" autofocus='false'> <label for="title"><b>Title</b></label> <input autofocus="true" type="text" placeholder="Post Title" name="title" value="<%= data.title %>"> <label for="body"><b>Content</b></label> <input id="x" type="hidden" name="body"" autofocus="false"> <!-- 此处存在语法错误 --> <trix-editor input="x" autofocus="false"> <%= data.body %> </trix-editor> <input type="submit" value="Update" class="btn"> </form>
解决步骤
修正语法错误
隐藏输入框name="body""多了一个双引号,会导致Trix初始化异常,修改为:<input id="x" type="hidden" name="body" autofocus="false">通过JavaScript强制控制焦点
Trix编辑器默认会在初始化时自动聚焦,仅设置autofocus="false"无法阻止该行为,需添加脚本手动干预:// Trix初始化完成后强制失焦 document.addEventListener('trix-initialize', (event) => { event.target.blur(); }); // 页面加载完成后,让标题输入框获得焦点 window.addEventListener('load', () => { document.querySelector('input[name="title"]').focus(); });
添加上述代码后,页面加载时焦点会自动落在标题输入框,可正常编辑其他文本框,同时不影响Trix编辑器的正常使用。
内容的提问来源于stack exchange,提问作者Kenan
相关产品推荐
相关产品推荐

