javascript
JavaScript标准Selection操作
- 簡介
- 術語
- 屬性
- 方法
- document.activeElement
- document.designMode = 'on';
簡介
selection是對當前激活選中區(即高亮文本)進行操作。
在非IE瀏覽器(Firefox、Safari、Chrome、Opera)下可以使用window.getSelection()獲得selection對象,本文講述的是標準的selection操作方法。文中絕大部分內容來自?https://developer.mozilla.org/en/DOM/Selection
術語
以下幾個名詞是英文文檔中的幾個名詞。
anchor屬性
anchorNode方法
getRangeAt(index)index:參考rangeCount屬性。
返回:根據下標index返回相應的range對象。
parentNode:焦點(插入符)將會在此節點內。
offset: 取值范圍應當是[0, 1, 2, 3, parentNode.childNodes.length]。
- 0:定位到第一個子節點前。
- 1:第二個子節點前。
- ……
- childNodes.length-1:最后一個子節點前。
- childNodes.length:最后一個子節點后。
“起點”不會移動,新的selection是從“起點”到“結束點”的區域,與方向無關(新的“結束點”可以在原“起點”的前面)。
parentNode:焦點將會在此節點內。
Offset:1,parentNode的最后;0,parentNode的最前。
alter:改變的方式。”move”,用于移動焦點;”extend”,用于改變selection。
direction:移動的方向。可選值forward | backword或left | right
granularity:移動的單位或尺寸。可選值,character", "word", "sentence", "line", "paragraph", "lineboundary", "sentenceboundary", "paragraphboundary", or "documentboundary"。
Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1才會支持此函數,官方文檔:https://developer.mozilla.org/en/DOM/Selection/modify
注意Chrome不允許同時存在多個range,它的處理方式和Firefox有些不同。
Chrome目前沒有改函數,即便是在Firefox中如果用自己創建(document.createRange())的range作為參數也會報錯。
如果用oSelction.getRangeAt()取到的,則不會報錯。
aNode:要驗證的節點。
aPartlyContained:true,只要aNode有一部分屬于selection就返回true;false,aNode必須全部屬于selection時才返回true。
document.activeElement
該屬性屬于HTML5中的一部分,它返回當前獲得焦點的元素,如果不存在則返回“body”。一般情況下返回的是“文本域”或“文本框”。也有可能返回“下拉列表”、“按鈕”、“單選”或“多選按鈕”等等,Mac OS系統中可能不會返回非輸入性元素(textbox,例如文本框、文本域)。
相關屬性和方法:
selectionStart- 如果textbox沒有selection時,selectionStart和selectionEnd相等,都是焦點的位置。
- 在使用setSelectionRange()時
如果end小于start,會講selectionStart和selectionEnd都設置為end;
如果start和end參數大于textbox內容的長度(textbox.value.length),start和end都會設置為value屬性的長度。 - 值得一提的是selectionStart和selectionEnd會記錄元素最后一次selection的相關屬性,意思就是當元素失去焦點后,使用selectionStart和selectionEnd仍能夠獲取到元素失去焦點時的值。這個特性可能會對制作“插入表情”時十分有用(將表情插入到元素最后一次焦點的位置)。
支護性:ie6\7\8不支持;Chrome、Firefox、Opera、Safari都支持。
參考文檔:https://developer.mozilla.org/en/DOM/document.activeElement
document.designMode = 'on';
當document.designMode = 'on'時selection的方法、selectionStart、selectionEnd在Firefox和Opera中不可以使用,但Chrome和Safari可以。
轉載于:https://www.cnblogs.com/andydao/p/3401201.html
總結
以上是生活随笔為你收集整理的JavaScript标准Selection操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 新建文件夹
- 下一篇: StringBuilder/String