1、實例1,設置網頁選中內容而且複製到黏貼板html
<p id='txtone'>發的FDSAFSDFDS!其實無論哪一個行業,
<img src='http://beijing.gongjuji.net/imgdata/big/4ba6635a-1e69-42b1-b64d-c25f655b4152.jpg'/>
都會遇到這個問題。因此企業員工自身幸福感很重要,若連員工都不幸福,他們怎麼能提供客戶滿意的服務呢?更況且做爲客服人員,若是本身都不快樂,他們又怎麼能去提高別人的心理資本,去增長他們的幸福感呢?快樂員工高效工做不該該僅僅只是一句口號而已~
</p>
<button id="button">選中一些文字,而後點擊本按鈕</button>
<script>
var oBtn = document.getElementById("button");
oBtn.onclick = function () {
var range = document.createRange();
var node1 = document.getElementById('txtone');
range.selectNode(node1);
var userSelection;
if (window.getSelection) { //現代瀏覽器
userSelection = window.getSelection();
} else if (document.selection) { //IE瀏覽器 考慮到Opera,應該放在後面
userSelection = document.selection.createRange();
}
//設置選中區域
userSelection.addRange(range);
//執行命令複製複製到黏貼板
document.execCommand('Copy',false,null);
};
</script>
2、其餘node
IE:document.selection chrome
FireFox:window.getSelection() 瀏覽器
document.selection只有IE支持,緩存
window.getSelection()也只有FireFox和 Safari支持,都不是標準語法。
selection 對象
--------------------------------------------------------------------------------
表明了當前激活選中區,即高亮文本塊,和/或文檔中用戶可執行某些操做的其它元素。
selection 對象的典型用途是做爲用戶的輸入,以便識別正在對文檔的哪一部分正在處理,或者做爲某一操做的結果輸出給用戶。
用戶和腳本均可以建立選中區。用戶建立選中區的辦法是拖曳文檔的一部分。腳本建立選中區的辦法是在文本區域或相似對象上調用 select 方法。要獲取當前選中區,請對 document 對象應用 selection 關鍵字。要對選中區執行操做,請先用 createRange 方法從選中區建立一個文本區域對象。
一個文檔同一時間只能有一個選中區。選中區的類型決定了其中爲空或者包含文本和/或元素塊。儘管空的選中區不包含任何內容,你仍然能夠用它做爲文檔中的位置標誌。app
#如下代碼在IE瀏覽器中生效編輯器
// 對選定的文字進行加粗函數
document.selection.createRange().execCommand("Bold")post
// 獲取選定的文本優化
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到第二個字符後面
Js代碼
- 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);
保存選定區
Js代碼
- 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;
- }
載入選定區
Js代碼
- function setSelectionRange(savedSel )
- {
- if( ! savedSel )
- return;
- if( window.getSelection )
- {
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(savedSel);
- }
- else if( document.selection )
- {
- savedSel.select();
- }
- };
一、獲取光標位置
Js代碼
- 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;
- }
2.設置光標位置
Js代碼
- 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(); // 選定當前區域
- }
- }
三、將光標移動到輸入框
ctrl.focus();
插入指定元素到指定位置的相關代碼:
Html代碼
- <!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()" />
- <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>
- </body>
- </html>
簡易富文本編輯器:

代碼:
Html代碼
- <!doctype html>
- <html>
- <head>
- <title>selection</title>
- </head>
- <body>
- <input type="text" name="txt" id="txt" />
- <input type="button" value="移動光標" onclick="setCaretPosition(2)" />
-
- <p id="p1" contenteditable="true"><b>Hello</b> World</p>
- <input type="button" value="insertSpanToFirst" onclick="insertSpan()" />
- <input type="button" value="insertHTMLByJS" onclick="insertHTMLByJS()" />
- <input type="button" value="insertHTMLByCommand" onclick="insertHTMLByCommand()" />
- <input type="button" value="insertImgByCommand" onclick="insertImgByCommand()" />
-
- <script>
- var p1element = document.getElementById('p1');
- var cacheRange = null;
- p1element.onkeydown = function(e){
- //alert(e.keyCode);
- };
- p1element.onblur = function(){
-
- console.log('blur');
- var sel = window.getSelection();
- if(sel.rangeCount){
- cacheRange = sel.getRangeAt(0);
- cacheRange.anchorNode = sel.anchorNode;
- cacheRange.anchorOffset = sel.anchorOffset;
- cacheRange.focusNode = sel.focusNode;
- cacheRange.focusrOffset = sel.focusOffset;
- console.log(sel.anchorNode);
- console.log(sel.anchorOffset);
- }
-
- };
- function setCaretPosition(pos){
- var ctrl = document.getElementById('txt');
- //設置光標位置函數
- if(ctrl.setSelectionRange) {
- ctrl.select();
- 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();
- }
- }
- function insertSpan(){
- var oP1 = document.getElementById("p1");
- var oHello = oP1.firstChild;
- var oRange = document.createRange();
- var oSpan = document.createElement("span");
- oSpan.style.color = "red";
- oSpan.appendChild(document.createTextNode("Inserted text"));
-
- oRange.setStart(oHello, 0);
- oRange.setEnd(oHello, 0);
- oRange.insertNode(oSpan);
-
- var ctrl = document.getElementById('p1');
- //設置光標位置函數
- if(ctrl.setSelectionRange) {
- ctrl.select();
- 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();
- }
- }
- function insertHTMLByJS(){
- if(cacheRange === null) return;
-
- var appendEl = document.createElement("span");
- appendEl.textContent = "this is span";
- appendEl.style.color = "blue";
-
- // var appendEl = document.createElement("span");
- // appendEl.style.width = "100px";
- // appendEl.style.height = "60px";
- // appendEl.style.display = "inline-block";
- // appendEl.style.background = "left top no-repeat url(https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png)";
- // appendEl.innerHTML = " ";
-
- // 方式1,經過新建立的選定區來插入
- // var oRange = document.createRange();
- // console.log(cacheRange);
- // oRange.setStart(cacheRange.anchorNode, cacheRange.anchorOffset);
- // oRange.insertNode(appendEl);
-
-
- // 方式2,經過緩存以前的選定區來插入
- var sel = window.getSelection();
- sel.removeAllRanges();
- cacheRange.insertNode(appendEl);
-
- if( ! sel.isCollapsed ){
- sel.collapseToEnd();
- }
- sel.addRange(cacheRange);
- // 移除光標顯示
- document.getElementById('p1').blur();
- sel.removeAllRanges();
- cacheRange = null;
-
- }
- function insertHTMLByCommand(){
- if(cacheRange === null) return;
-
- // 方式2,經過緩存以前的選定區來插入
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(cacheRange);
- document.execCommand("insertHTML", "false", "<span style='color:#ff3300'><img src='https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png' width=50 height=50 /></span>");
- // 移除光標顯示
- document.getElementById('p1').blur();
- sel.removeAllRanges();
- cacheRange = null;
-
- }
- function insertImgByCommand(){
- if(cacheRange === null) return;
-
- // 方式2,經過緩存以前的選定區來插入
- var sel = window.getSelection();
- if( ! sel.isCollapsed ){
- sel.collapseToEnd();
- }
- sel.addRange(cacheRange);
- document.execCommand("insertImage", "false", "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png");
- // 移除光標顯示
- document.getElementById('p1').blur();
- sel.removeAllRanges();
- cacheRange = null;
-
- }
-
- </script>
- </body>
- </html>
遇到的坑,優化編輯框點擊後有時沒法成爲編輯狀態的問題
優化代碼以下:
Js代碼
- /* 優化編輯框點擊後有時沒法成爲編輯狀態的問題 */
- var editor = document.getElementById('editor_id'), editorTimer = null;
- editor.addEventListener('click', function(){
- console.log('click');
- editorTimer = setTimeout(function(){
- console.log('set focus');
- var sel,range;
- if (window.getSelection && document.createRange) {
- range = document.createRange();
- range.selectNodeContents(editor);
- range.collapse(true);
- range.setEnd(editor, editor.childNodes.length);
- range.setStart(editor, editor.childNodes.length);
- sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(range);
- } else if (document.body.createTextRange) {
- range = document.body.createTextRange();
- range.moveToElementText(editor);
- range.collapse(true);
- range.select();
- }
- editor.focus();
- },300);
- }, false);
- editor.addEventListener('focus', function(){
- console.log('focus');
- clearTimeout(editorTimer);
- }, false);
更多:
JS Range使用整理
HTML5 瀏覽器返回按鈕/手機返回按鈕事件監聽
瀏覽器記住密碼整理(三)