我想做什么:
我知道一些基本的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??
});
答案 0 :(得分:3)
您可能需要做很多事情,但这样的事情应该足以让您入门:
$("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小提琴中看到一个例子:
http://jsfiddle.net/igor_9000/4zk5otvm/2/
您可能需要添加更多内容,具体取决于您希望能够对该功能执行的操作以及您希望执行的限制,但这应该足以让您入门。希望有所帮助!
答案 1 :(得分:0)
这仅支持现代浏览器,如果您想支持旧版浏览器,则需要获取计算selectionStart的方法。这未经过全面测试,如果双击所选的一行,则会切换短划线。当你设置新值时,选择就会消失。
$("textarea").on("dblclick", function (evt) {
var taValue = this.value;
//if there is no text than there is nothing to do
if(!taValue.length) return;
//get the position of the selection (not supported old browsers)
var se = this.selectionStart;
//find where the previous line break is located (array lastIndexOf not supported old browsers)
//thinking about it, probably do not need to split... :)
var loc = taValue.substr(0, se).split("").lastIndexOf("\n")+1;
//separate the text by characters
var parts = taValue.split("");
//if the character is a -, than remove it
if (parts[loc]==="-") {
parts.splice(loc, 1);
} else { //else inject the -
parts.splice(loc, 0, "-");
}
//join the array back up into a string and set the value
this.value = parts.join("");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows=10 cols=30>FOO FOO FOO
BAR BAR BAR
CAKE CAKE CAKE
WORLD WORLD WORLD</textarea>
&#13;