【问题标题】:Find text by search and highlight current result only通过搜索查找文本并仅突出显示当前结果
【发布时间】:2017-02-14 03:56:09
【问题描述】:

尝试仅突出显示当前/单个文本,例如浏览器“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/
有什么解决办法吗?

【问题讨论】:

  • 您只想突出显示第一个结果?
  • 是的............
  • 您要搜索的是mark.js

标签: javascript jquery regex search highlight


【解决方案1】:

您可以向当前目标添加一个类。我更改的代码行:

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

【讨论】:

  • 嗨,谢谢,但第一次搜索正常,当搜索另一个文本(第二次)时找不到:请在我的网站上查看:glass2.com/instruction-manual
  • 当搜索另一个文本(第二次)时,它会发现“绘图示例”(每次)都找不到确切的文本。检查:glass2.com/instruction-manual
  • @Aariba 你有这个 id ray-all_textduplicated ID 必须是唯一的,这可能会破坏 JS
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 2018-03-25
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2011-05-05
相关资源
最近更新 更多