TextRangeオブジェクトを使った文字の後方/前方検索2
Based on NCSA Mosaic. NCSA Mosaic(TM); was developed at the National Center for Supercomputing Applications at the University of Illinois at Urbana-Champaign.atatatatat
Distributed under a licensing agreement with Spyglass, Inc.
Contains security software licensed from RSA Data Security Inc.
Portions of this software are based in part on the work of the Independent JPEG Group.
Contains SOCKS client software licensed from Hummingbird Communications Ltd.
Contains ASN.1 software licensed from Open Systems Solutions, Inc.
Multimedia software components, including Indeo(R); video, Indeo(R) audio, and Web Design Effects are provided by Intel Corp.
Unix version contains software licensed from Mainsoft Corporation. Copyright (c) 1998-1999 Mainsoft Corporation. All rights reserved. Mainsoft is a trademark of Mainsoft Corporation.
Warning: This computer program is protected by copyright law and international treaties. Unauthorized reproduction or distribution of this program, or any portion of it, may result in severe civil and criminal penalties, and will be prosecuted to the maximum extent possible under the law.
1つ前のサンプルでは、前方検索したあとの後方検索、および後方検索したあとの前方検索で、
1つ前に検索した文字列が重複して検索されてしまう。それを解決するのが
このサンプル。グローバル変数selectAreaを宣言し、
検索が実行されるごとに、selectした範囲をbookmarkに記憶する。
そして、次に検索するとき、そのbookmarkを呼び出して、再びselect()し、
後方検索ならcollapse(false)でカーソルをbookmarkのレンジの末尾、
前方検索ならcollapse(true)でカーソルをbookmarkのレンジの先頭に移動し、
findText()する。findText(str,1)なら文字列strを後方検索、
findText(str,-1)なら前方検索する。
if(selectArea != "")内の条件内は、初回の検索では実行されない。
<SCRIPT LANGUAGE="JavaScript">
var rng
function makeTR() {
rng = document.body.createTextRange();
rng.collapse(true)
}
var selectArea = ""
function searchE(str) {
if(str != "") {
if(selectArea != "") {
rng.moveToBookmark(selectArea)
rng.collapse(false); //カーソルを選択された文字の末尾に移動
}
rng.findText(str,1)
rng.select()
selectArea = rng.getBookmark()
}
}
function searchF(str) {
if(str != "") {
if(selectArea != "") {
rng.moveToBookmark(selectArea)
rng.collapse(true); //カーソルを選択された文字の先頭に移動
}
rng.findText(str,-1)
rng.select()
selectArea = rng.getBookmark()
}
}
</SCRIPT>