mousedown与click事件差异:自定义编辑器焦点失效问题
自定义编辑器mousedown事件下焦点失效问题
我正在从零构建一款自定义编辑器,原本通过click事件处理器实现光标移动并聚焦<input>元素,但为了实现选区功能,将事件改为mousedown后,点击时<input>的焦点功能失效。
相关代码
mousedown事件处理器
document.querySelector(".tab-editor").addEventListener("mousedown", (e) => { var rect = document.querySelector("#line-1").getBoundingClientRect(); var x = e.x - rect.x; var y = e.y - rect.y; const line = Math.ceil(y / 20); writer.moveCursorTo(x, line); }
writer.moveCursorTo()方法
if (line > this.lines.length){line = this.lines.length;} if (line < 1) {line = 1;} this.lines[this.currentline - 1].setCurrent(false); this.currentline = line; this.lines[this.currentline - 1].setCurrent(true); cursor.setPos(cursor.x, line * 20 - 20) // set y pos cursor.moveApproxX(x, this.lines[this.currentline - 1].text()); // set x pos
cursor.setPos()方法
this.cursor().style.left = x+"px"; this.cursor().style.top = y+"px"; this.input().style.left = x+"px"; this.input().style.top = y+"px"; this.x = x; this.y = y; this.input().focus(); this.resetBlink();
经检查,click和mousedown事件中的x、y参数一致。
问题验证测试代码
- 可正常工作的代码:
document.querySelector(".tab-editor").addEventListener("click", e=>document.querySelector('.editor-input').focus())
- 无法工作的代码:
document.querySelector(".tab-editor").addEventListener("mousedown", e=>document.querySelector('.editor-input').focus())
内容的提问来源于stack exchange,提问作者anom907 zat
相关产品推荐
相关产品推荐

