gpt4 book ai didi

javascript - onFocus 没有通过 selectionStart 获取光标位置

转载 作者:行者123 更新时间:2023-11-30 20:43:55 26 4
gpt4 key购买 nike

我正在尝试获取用户在文本框上单击的插入符号位置。我想在用户点击输入的位置添加一定的文本。我正在尝试在 inputonFocus 方法中执行此操作。但是,e.target.selectionStart 总是给我 0

class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
value: "hello"
};
}

onFocus = e => {
console.log(e.target.id);
console.log(e.target.selectionStart); // receiving only 0 here
};

onChange = e => {
this.setState({
value: e.target.value
});
};

render() {
return (
<input
id="my-input"
onChange={this.onChange}
value={this.state.value}
onFocus={this.onFocus}
/>
);
}
}

感谢任何帮助

代码沙盒 https://codesandbox.io/s/6x623x50r

最佳答案

不是获取光标位置值 onFocus 事件,而是执行 onMouseUp 事件。当输入聚焦并且您单击同一输入中的其他位置时,不会调用 onFocus。

class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
value: "hello"
};
}

onMouseUp = e => {
console.log(e.target.id);
console.log(e.target.selectionStart);
};

onChange = e => {
this.setState({
value: e.target.value
});
};

render() {
return (
<input
id="my-input"
onChange={this.onChange}
value={this.state.value}
onMouseUp={this.onMouseUp}
/>
);
}
}

Working codeSandbox

获取selectionStart onFocus事件有bug,可以查看issue here

关于javascript - onFocus 没有通过 selectionStart 获取光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48941862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com