gpt4 book ai didi

Javascript 在双击时添加到文本区域中的行

转载 作者:行者123 更新时间:2023-11-29 19:15:02 25 4
gpt4 key购买 nike

我正在尝试做的事情:

  1. 双击文本区域中的一行。
  2. 防止文本被选中。
  3. 在该行前加一个破折号。

我知道一些基本的 jquery,但似乎无法理解所需的较低级别的 javascript。这是我目前所拥有的:

$("textarea").dblclick(function() {

//TODO: Prevent selection


//TODO: Get the line number??


//TODO: prepend a dash to the line
// or replace the line with itself
// plus the dash at the front??


});

Here is the fiddle .

最佳答案

您可能需要做很多事情,但这样的事情应该足以让您开始:

$("textarea").dblclick(function() {
//first, get the position of the cursor
var cursorPosition = $(this).prop("selectionStart");

//get the text value at the cursor position
var textValue = $(this).val().substr(cursorPosition,1);

//use a loop to look backward until we find the first newline character \n
while(textValue != '\n' && cursorPosition >= 0) {
cursorPosition--;
textValue = $(this).val().substr(cursorPosition,1);
}
//update the textarea, combining everything before the current position, a dash, and everything after the current position.
$(this).val(($(this).val().substr(0,cursorPosition+1) + '-' + $(this).val().substr(cursorPosition+1)))

});

你可以在这个 JS Fiddle 中看到一个例子:

http://jsfiddle.net/igor_9000/4zk5otvm/2/

您可能需要添加更多内容,具体取决于您希望使用该函数执行的操作以及您希望执行的限制,但这应该足以让您入门。希望对您有所帮助!

关于Javascript 在双击时添加到文本区域中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992390/

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