jquery搜尋關鍵詞高亮效果

antzone發表於2017-04-18

分享一段程式碼例項,它實現了搜尋關鍵詞高亮效果。

這樣的效果在實際應用中非常多見,主要為了突出關鍵詞的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.highlight {
  background-color: #f00;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
function highlight(text, words, tag) {
  tag = tag || 'span';
  var index, len = words.length,
    reg;
  for (index = 0; index < len; index++) {
    reg = new RegExp(words[index], 'g');
    if (reg.test(text)) {
      text = text.replace(reg, '<' + tag + ' class="highlight">$&</' + tag + '>');
    }
  }
  return text;
}
 
function unhighlight(text, tag) {
  tag = tag || 'span';
  var reg = new RegExp('(<' + tag + '.+?>|<\/' + tag + '>)', 'g');
  return text.replace(reg, '');
}
$(document).ready(function() {
  $('.btn').click(function(event) {
    var str = $(".search").val();
    var strArr = [];
    str = str.trim(); //去掉兩端空格
    if (str === "") {
      alert("關鍵字為空");
      return false;
    } else {
      //支援多詞
      if (str.split(" ").length != 1) {
        strArr = str.split(" ");
      } else {
        strArr.push(str);
      }
    }
    //console.log(strArr);
    $('#box').html(unhighlight(
      $('#box').html(),
      'strong'
    ));
    $('#box').html(highlight(
      $('#box').html(),
      strArr,
      'strong'
    ));
  });
}) 
</script>
</head>
<body>
  <div>
    <input type="text" class="search">
    <button class="btn">搜尋</button>
  </div>
  <div id="box">本站的url地址是<a href="http://www.softwhy.com" target="_blank">www.softwhy.com</a></div>
</body>
</html>

相關文章