2016-10-05 1 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

привет, спасибо, но первый поиск работает, когда поиск другой текст (второй раз), то он не может найти: пожалуйста, проверьте мой сайт: http://www.glass2.com/instruction-manual – Aariba

+0

при поиске другого текста (второй раз), затем он найдет «ЧЕРТЕЖНЫЙ ПРИМЕР» (каждый раз) не найти точный текст. check: http://www.glass2.com/instruction-manual – Aariba

+1

@Aariba у вас есть этот идентификатор id-ray-all_text'duplicated ID, который может быть разбит на JS – DaniP

Смежные вопросы