2016-10-05 22 views
2

ブラウザの "Control-F"キーボードコマンド検索のように、現在のテキストのみを強調表示しようとしています。検索がうまくいけば、次の/新しいテキストを見つける。しかし、それはすべての結果をハイライトし、現在の結果/テキストのみを強調表示しています。以下検索でテキストを検索し、現在の結果のみを強調表示

JS:

$('body').on('keydown', '#searchfor', function(e) { 
    if (e.which === 32 && e.target.selectionStart === 0) { 
     return false; 
    } 
}); 

//Create some vars to later check for: 
//['text you are searching', 'number of highlights','actual highlight'] 
var searching, 
    limitsearch, 
    countsearch; 

$('button#search').click(function() { 
    var searchedText = $('#searchfor').val(); 
    var page = $('#ray-all_text'); 

    //Now check if the text on input is valid 
    if (searchedText != "") { 
     //If the actual text on the input is different from the prev search 
     if(searching != searchedText) { 
      page.find('span').contents().unwrap(); 
      var pageText = page.html(); 
      var theRegEx = new RegExp("(" + searchedText + ")", "igm"); 
      var newHtml = pageText.replace(theRegEx, "<span>$1</span>"); 
      page.html(newHtml); 
      //Set your variables to the actual search 
      searching = searchedText; 
      limitsearch = page.find('span').length; 
      countsearch=0; 
     } else { 
      //If it's the same of the prev search then move to next item instead of repaint html 
      countsearch<limitsearch-1 ? countsearch++ : countsearch=0; 
      console.log(countsearch+'---'+limitsearch) 
     } 
     //Go to target search 
     $('body').animate({ 
      scrollTop: $("#ray-all_text span").eq(countsearch).offset().top - 50}, 
     200); 
    } else { 
     alert('empty search') 
    } 
}); 

HTML:

<div class="ray-search"> 
    <div class="field" id="ray-search-form"> 
    <input type="text" id="searchfor" placeholder="what are you searching for?" /> 
    <button type="button" id="search">Press to Find!</button> 
    </div> 
</div> 

<article id="ray-all_text"> 
    <p> 
    This manual and web site, all information and data and photos contained herein, are the s... 
    </p> 
</article> 

例を確認してください:https://jsfiddle.net/gaezs6s8/3/
あり任意のソリューションを?

+0

はあなただけ**最初の**の結果を強調したいですか? – nem035

+0

はい............ – Aariba

+0

あなたが探しているのは[mark.js](https://markjs.io) – dude

答えて

5

現在のターゲットにクラスを追加できます。あなたのコードから行私は変更:

var actual = $("#ray-all_text span").eq(countsearch); 
$('.active').removeClass('active'); 
actual.addClass('active'); 
$('body').animate({ 
    scrollTop: actual.offset().top - 50}, 
200); 

とCSSの:

#ray-all_text span.active { 
    background-color:yellow; 
} 

Demo Fiddle

+0

です。こんにちは、ありがとうございますが、最初の検索は動作しています。テキスト(2回目)してから見つけることができません:私のサイトをチェックしてください:http://www.glass2.com/instruction-manual – Aariba

+0

別のテキストを検索すると(2回目)、 "DRAWING EXAMPLE" )正確なテキストが見つかりません。チェック:http://www.glass2.com/instruction-manual – Aariba

+1

@AaribaあなたはこのIDを持っています 'ray-all_text'複製IDはユニークでなければなりません。それはJSを破る可能性があります。 – DaniP

関連する問題