gpt4 book ai didi

javascript - Textarea 和 tab 键 : Get\t instead of jumping to the next element

转载 作者:行者123 更新时间:2023-11-27 23:10:32 25 4
gpt4 key购买 nike

我正在使用一个名为 userInput 的 html 文本区域,但每当我按下 Tab 键时,它就会移动到下一个元素。我如何让制表键创建一个制表符或至少一些空格,而不是移动到下一个元素?

最佳答案

为 keydown 事件添加一个事件监听器,如果它是一个已被按下的选项卡,则阻止该事件:

var ta = document.getElementById("ta");

ta.addEventListener("keydown", function(e) { // when a keydown happens
if(e.keyCode === 9) { // if the key that is pressed is a tab (keyCode 9)
var start = this.selectionStart, // get the selection start (or the cursor position if nothing is selected)
end = this.selectionEnd, // get the selection end (or the cursor position if nothing is selected)
value = this.value;
this.value = value.substr(0, start) + "\t" + value.substr(end); // add a tab in-between instead of the selected text (or at cursor position if nothing is selected)
this.selectionStart = this.selectionEnd = start + 1; // set the cursor to one character after the last start index (right after the newly added tab character)
e.preventDefault(); // IMPORTANT: prevent the default behavior of this event (jumps to the next element and give it focus)
}
})
#ta {
width: 100%;
height: 170px;
}
<textarea id="ta"></textarea>

关于javascript - Textarea 和 tab 键 : Get\t instead of jumping to the next element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46249188/

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