您的位置:首页 > 其它

光标所在位置插入一串字符,并在特定位置设置光标锁定位置

2016-04-13 13:57 531 查看
在写一个小型的编辑器时,有很多的鼠标点击事件,用于设定markdown语法。那么如何获取光标的所在位置,并插入一串字符,且将光标定位到特定位置?

接下来就是在网上查看的方法以及如何实现该功能的代码:

talk is cheap,show me the code

showdownContainer.prototype.insertStrAtCursor = function(textareaObj,insertString){//IE support
if (document.selection) {
textareaObj.focus();
var sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}
//MOZILLA/NETSCAPE support
else if (textareaObj.selectionStart || textareaObj.selectionStart == '0') {
var startPos = textareaObj.selectionStart;
var endPos = textareaObj.selectionEnd;
// save scrollTop before insert
var restoreTop = textareaObj.scrollTop;
textareaObj.value = textareaObj.value.substring(0, startPos) + insertString + textareaObj.value.substring(endPos, textareaObj.value.length);
if (restoreTop > 0) {
// restore previous scrollTop
textareaObj.scrollTop = restoreTop;
}
textareaObj.focus();
textareaObj.selectionStart = startPos + insertString.length;
textareaObj.selectionEnd = startPos + insertString.length;
} else {
textareaObj.value += insertString;
textareaObj.focus();
}
};
/**
* 设置光标位置
* @param textareaObj  文本域元素对象
* @param insertString  待插入的字符串
* @param posLen 定位光标在插入字符串的第几个字符处
*/
showdownContainer.prototype.setCursorPosition = function(textareaObj,insertString,posLen){
var cursorPosition = 0;
if(textareaObj.selectionStart){
cursorPosition = textareaObj.selectionStart;
}
this.insertStrAtCursor(textareaObj,insertString);
textareaObj.focus();
textareaObj.setSelectionRange(textareaObj.value.length,cursorPosition + posLen);
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: