2
range.expand('word')
を使って単語をカバーするように範囲を作ったとします。通常、次の単語を追加するには、range.moveEnd('word', 1)
と書きます。しかし、これはWebkitではうまくいかないようです。多分実装されるべきでしょうか?Webkitでは、範囲に別の単語を追加するにはどうすればよいですか?
range.expand('word')
を使って単語をカバーするように範囲を作ったとします。通常、次の単語を追加するには、range.moveEnd('word', 1)
と書きます。しかし、これはWebkitではうまくいかないようです。多分実装されるべきでしょうか?Webkitでは、範囲に別の単語を追加するにはどうすればよいですか?
あなたはTextRange
について話していますが、これは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 –