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