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 –