<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>haiyang.me > input輸入框獲取光標位置,在光標處插入文字,替換選中文字</title>
<script>
//獲取光標位置函數
function getCursorPosition(elem) {
var pp = 0
// IE
if (document.selection) {
elem.focus()
var aa = document.selection.createRange()
aa.moveStart('character', -elem.value.length)
pp = aa.text.length
}
// FF, Chrome
else if (elem.selectionStart || elem.selectionStart == '0') {
pp = elem.selectionStart
}
return pp
}
//設置光標位置函數
function setCaretPosition(elem, pos) {
// IE
if (elem.setSelectionRange) {
elem.focus()
elem.setSelectionRange(pos, pos)
}
// FF, Chrome
else if (elem.createTextRange) {
var range = elem.createTextRange()
range.collapse(true)
range.moveEnd('character', pos)
range.moveStart('character', pos)
range.select()
}
}
function insertAtCursor(elem, value) {
var field = elem
var newValue = ''
// IE support
if (document.selection) {
field.focus()
var sel = document.selection.createRange()
sel.text = newValue = value
sel.select()
} else if (field.selectionStart || field.selectionStart === 0) {
var startPos = field.selectionStart
var endPos = field.selectionEnd
var restoreTop = field.scrollTop
newValue = field.value.substring(0, startPos) +
value +
field.value.substring(endPos, field.value.length)
if (restoreTop > 0) {
field.scrollTop = restoreTop
}
field.value = newValue
field.focus()
setTimeout(function () {
field.selectionStart = startPos + value.length
field.selectionEnd = startPos + value.length
}, 0)
} else {
newValue = field.value + value
field.value = newValue
field.focus()
}
}
</script>
</head>
<body>
<input id="a" type=text name=text1 value="1234567890">
<button onclick="alert(getCursorPosition(a))">獲取光標位置</bottun>
<button onclick="setCaretPosition(a, 5)">設置光標位置: 5</bottun>
<button onclick="insertAtCursor(a, 'ww')">替換或插入文字: ww</bottun>
</body>
<script>
'undefined' === typeof _trfq || (window._trfq = []);
'undefined' === typeof _trfd && (window._trfd = []), _trfd.push({
'tccl.baseHost': 'secureserver.net'
}), _trfd.push({
'ap': 'cpsh-oh'
}, {
'server': 'sg2plzcpnl458828'
}, {
'id': '7677590'
}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.
</script>
<script src='https://img1.wsimg.com/tcc/tcc_l.combined.1.0.6.min.js'></script>
</html>
複製代碼