现在的位置: 首页 > 综合 > 正文

Tag Archives: selectionStart

2013年09月10日 ⁄ 综合 ⁄ 共 745字 ⁄ 字号 评论关闭
需要实现:在光标位置处插入文字,以及获取焦点后光标位置处于文字末尾。
以前一直没有做过,今天了解了一下后实现并记录在此。
各浏览器TextArea获得焦点后的光标位置情况:
textarea.focus()

FireFox: 所有文字结束处
IE: 文字开头
Opera: 文字开头
Chrome: 文字开头
Safari: 文字开头

IE支持document.selection
Firefox,Chrome,Safari以及Opera都有selectionStart和selectionEnd属性
针对浏览器的特性进行判断并实现,代码如下:

function insertText(obj,str) {
if (document.selection) {
var sel = document.selection.createRange();
sel.text = str;
} else if (typeof obj.selectionStart === ‘number’ && typeof obj.selectionEnd === ‘number’) {
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
cursorPos += str.length;
obj.selectionStart = obj.selectionEnd = cursorPos;
} else {
obj.value += str;
}
}
function moveEnd(obj){
obj.focus();
var [...]

抱歉!评论已关闭.