双击时,Javascript在文本区域中前置到行
我想做的是:双击时,Javascript在文本区域中前置到行,javascript,jquery,Javascript,Jquery,我想做的是: 双击文本区域中的一行 禁止选择文本 在那条线前加一个破折号 我知道一些基本的jquery,但似乎不理解所需的较低级别javascript。以下是我到目前为止的情况: $("textarea").dblclick(function() { //TODO: Prevent selection //TODO: Get the line number?? //TODO: prepend a dash to the line // or replace th
$("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小提琴中看到一个示例:
您可能还需要添加更多内容,具体取决于您希望对函数执行的操作以及您希望强制执行的限制,但这应该足以让您开始。希望有帮助 这只支持现代浏览器,如果您想支持较旧的浏览器,则需要获取计算selectionStart的方法。这不是完全测试的,如果双击选定的线,它将切换破折号。设置新值时,选择将消失
$(“textarea”)。在(“dblclick”,函数(evt){
var taValue=此.value;
//如果没有文本,就没有什么可做的
如果(!taValue.length)返回;
//获取所选内容的位置(旧浏览器不支持)
var se=this.selectionStart;
//查找上一个换行符的位置(旧浏览器不支持的数组lastIndexOf)
//想一想,可能不需要拆分…:)
var loc=taValue.substr(0,se).split(“”).lastIndexOf(“\n”)+1;
//用字符分隔文本
var parts=taValue.split(“”);
//如果字符为-,则将其删除
如果(部分[loc]==“-”){
零件拼接(loc,1);
}else{//else注入-
零件拼接(loc,0,“-”);
}
//将数组重新连接到字符串中并设置值
this.value=parts.join(“”);
});代码>
福福福
酒吧
蛋糕蛋糕
世界
这根本不是一项简单的任务。要了解所选的行,您必须深入了解文本选择范围以及硬/软新行的各种不好之处。我建议你看看Rangy插件,因为它至少可以让你开始。textarea中的文本是预定义的还是用户可以添加到其中?我之所以这样说,是因为您必须首先获得文本区域中的行数。此外,为了防止选择,您可以在css中添加csstextarea::selection{background:none;}
textarea::-moz selection{background:none;}