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

當搜索另一個文本(第二次),然後找到「繪圖示例」(每次)找不到確切的文字。檢查:http://www.glass2.com/instruction-manual – Aariba

+1

@Aariba你有這個ID'ray-all_text'duplicated ID的唯一是唯一的,可以打破JS – DaniP

相關問題