我正在尝试做的事情:
- 双击文本区域中的一行。
- 防止文本被选择。
- 在该行前面添加一个破折号。
我知道一些基本的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??
});
最佳答案
您可能需要做很多事情,但这样的事情应该足以让您开始:
$("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/