document.selection : IE
window.getSelection() :Chrome、Safari、FireFox
selection代表了當前激活選中區,即高亮文本塊,和/或文檔中用戶可執行某些操作的其它元素。
對象的典型用途是作為用戶的輸入,以便識別正在對文檔的哪一部分正在處理,或者作為某一操作的結果輸出給用戶。
**** 用戶和腳本都可以創建選中區 ****
用戶創建選中區的辦法是拖曳文檔的一部分。
腳本創建選中區的辦法是在文本區域或類似對象上調用select方法。
要獲取當前選中區,請對document對象應用selection關鍵字。
要對選中區執行操作,請先用createRange方法從選中區創建一個文本區域對象。
一個文檔同一時間只能有一個選中區。選中區的類型決定了其中為空或者包含文本和/或元素塊。盡管空的選中區不包含任何內容,你仍然可以用它作為文檔中的位置標志。
#以下代碼在IE瀏覽器中生效
// 對選定的文字進行加粗
document.selection.createRange().execCommand("Bold")
// 獲取選定的文本
document.selection.createRange().text
// 獲取選定的html
document.selection.createRange().htmlText
// 清除選定的內容
document.selection.clear()
// 彈出選擇區的類型( None,Text,...)
document.selection.type
// 獲取選取區的文字
var range = document.selection.createRange(); // 創建文本區域對象
range.moveStart("character",2); // 選定區起始點向后移動2個字符
range.moveEnd("character",1); // 選定區結束點向后移動1個字符
console.log(range.text)
#以下代碼在chrome/firefox中生效
window.getSelection().rangeCount // 獲取選定區數量
window.getSelection().isCollapsed // 選取定區起始點是否重疊
// 在光標處插入圖片
document.execCommand("insertImage","false","https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png")
// 在光標處插入html代碼
document.execCommand("insertHTML","false","<br/>")
// 在焦點狀態下,移動光標至第一個字符后面
document.getElementById('txt').select();
document.getElementById('txt').setSelectionRange(1,1)
// 復制選定文本到剪切板
document.execCommand("Copy","false",null);
下面舉例:
// 插入span到第二個字符后面
var span = document.createElement('span');
span.innerHTML = '[this is add element]';
var sel = window.getSelection();
var startEl = $("#editor_id").next()[0].firstChild, startOffset = 2;
var range = document.createRange();
range.setStart(startEl, startOffset)
range.setEnd(startEl, startOffset);
range.collapse(true);
range.insertNode(span);
sel.removeAllRanges()
sel.addRange(range);
// 保存選定區
function saveSelectionRange()
{
if( window.getSelection )
{
var sel = window.getSelection();
if( sel.rangeCount > 0 ) return sel.getRangeAt(0);
}
else if( document.selection )
{
var sel = document.selection;
return sel.createRange();
}
return null;
}
// 載入選定區
function setSelectionRange(savedSel )
{
if( ! savedSel ) return;
if( window.getSelection )
{
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(savedSel);
}
else if( document.selection )
{
savedSel.select();
}
}
// 獲取光標位置
function getCursortPosition (ctrl)
{
//獲取光標位置函數
var CaretPos = 0;
// IE Support
if (document.selection)
{
ctrl.focus (); // 獲取焦點
var Sel = document.selection.createRange (); // 創建選定區域
Sel.moveStart('character', -ctrl.value.length); // 移動開始點到最左邊位置
CaretPos = Sel.text.length; // 獲取當前選定區的文本內容長度
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
{
CaretPos =ctrl.selectionStart; // 獲取選定區的開始點
}
return CaretPos;
}
// 設置光標位置
function setCaretPosition(ctrl, pos)
{
//設置光標位置函數
if(ctrl.setSelectionRange)
{
ctrl.focus(); // 獲取焦點
ctrl.setSelectionRange(pos,pos); // 設置選定區的開始和結束點
}
else if (ctrl.createTextRange)
{
var range = ctrl.createTextRange(); // 創建選定區
range.collapse(true); // 設置為折疊,即光標起點和結束點重疊在一起
range.moveEnd('character', pos); // 移動結束點
range.moveStart('character', pos); // 移動開始點
range.select(); // 選定當前區域
}
}
// 插入指定元素到指定位置
<!doctype html>
<html>
<head>
<title>selection</title>
</head>
<body>
<p id="p1" contenteditable="true"><b>Hello</b> World</p>
<input type="button" value="insertSpan" onclick="insertSpan()" />
</body>
<script>
function insertSpan() {
var oP1 = document.getElementById("p1");
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
var oSpan = document.createElement("span");
oSpan.style.color = "red";
oSpan.appendChild(document.createTextNode("Inserted text"));
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
oRange.insertNode(oSpan);
}
</script>
</html>