2
假設我使用range.expand('word')
來創建我的範圍,使其覆蓋單詞。通常要添加下一個單詞,我會寫range.moveEnd('word', 1)
。但是這似乎不適用於Webkit。也許它應該以不同的方式實施?在Webkit中,如何在範圍中添加另一個單詞?
假設我使用range.expand('word')
來創建我的範圍,使其覆蓋單詞。通常要添加下一個單詞,我會寫range.moveEnd('word', 1)
。但是這似乎不適用於Webkit。也許它應該以不同的方式實施?在Webkit中,如何在範圍中添加另一個單詞?
你說的是TextRange
s,它們只在IE中完全實現。其他瀏覽器使用DOM Level 2 Range對象,而在大多數情況下,它們遠遠優於TextRanges,但沒有與基於文本的方法(如expand()
)等效。然而,最近的WebKit瀏覽器確實實現了expand()
版本,並且Webkit和Firefox 4都具有提供類似功能的Selection
對象的modify()
方法。
實施例:http://jsfiddle.net/bzU22/1/
<script type="text/javascript">
function expandSelection() {
if (window.getSelection && window.getSelection().modify) {
var sel = window.getSelection();
sel.modify("extend", "forward", "word");
} else if (document.selection && document.selection.type == "Text") {
var range = document.selection.createRange();
range.moveEnd("word", 1);
range.select();
}
document.getElementById("test").focus();
}
</script>
<input type="button" unselectable onclick="expandSelection();" value="Expand">
<p contenteditable="true" id="test">Hello, this is some test text.
Select a word and then press the 'Expand' button.</p>
由於添。我以前使用var range = document.caretRangeFromPoint(x,y)。有沒有相當於我可以使用sel.modify? – tofutim
瀏覽器有不同的API。此問題有更多信息:http://stackoverflow.com/questions/3189812/creating-a-collapsed-range-from-a-pixel-position-in-ff-webkit –