迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中高亮显示文本

作者:迹忆客 最近更新:2024/03/22 浏览次数:

如果你一直想知道如何高亮显示 HTML 中的文本,并认为这将是一项复杂的任务,那就大吃一惊。在本 JavaScript 教程中,此任务将对你变得非常简单。

在本文中,我们将学习如何使用 JavaScript 高亮显示文本。


使用 JavaScript 中的 searchPrompt 方法高亮显示文本

将使用的第一种方法是通过 JavaScript 的提示高亮显示搜索文本。你可以将下面的 JavaScript 代码复制并粘贴到页面上。在按钮中调用函数 searchPrompt

searchPrompt 函数使用五个参数。这些参数解释如下:

  1. defaultSearchText 将一些文本值设置为默认高亮显示文本。
  2. isPrompt 有两个值 truefalse。如果你想通过提示接受高亮显示的文本值,则该值设置为 true。否则,将其设置为 false,并按默认搜索文本值自动搜索。
  3. 如果要将搜索文本视为单个短语,则将 treatAsPhrase 设置为 true,否则将其设置为 false
  4. textColor 这个参数是可选的。可以根据需要设置高亮显示的文本颜色,也可以将其保留为默认高亮显示的文本颜色为蓝色。
  5. bgColor 这个参数也是可选的。你可以将高亮显示的背景颜色设置为所需的颜色,或将其保留为默认高亮显示的背景颜色为黄色。

可以在下面找到用于此的 JavaScript 和 HTML 代码:

function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) {
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = '<font style=\'color:blue; background-color:yellow;\'>';
    highlightEndTag = '</font>';
  }

  var newText = '';
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();

  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i + 1);
    if (i < 0) {
      newText += bodyText;
      bodyText = '';
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf('>', i) >= bodyText.lastIndexOf('<', i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf('/script>', i) >=
            lcBodyText.lastIndexOf('<script', i)) {
          newText += bodyText.substring(0, i) + highlightStartTag +
              bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  return newText;
}

function highlightSearchTerms(
    searchText, treatAsPhrase, warnOnFailure, highlightStartTag,
    highlightEndTag) {
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(' ');
  }

  if (!document.body || typeof (document.body.innerHTML) == 'undefined') {
    if (warnOnFailure) {
      alert('the text is unavailable.');
    }
    return false;
  }

  var bodyText = document.body.innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(
        bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }

  document.body.innerHTML = bodyText;
  return true;
}

function searchPrompt(
    defaultSearchText, isPrompt, treatAsPhrase, textColor, bgColor) {
  // we can optionally use our own highlight tag values
  if ((!textColor) || (!bgColor)) {
    highlightStartTag = '';
    highlightEndTag = '';
  } else {
    highlightStartTag = '<font style=\'color:' + textColor +
        '; background-color:' + bgColor + ';\'>';
    highlightEndTag = '</font>';
  }

  if (treatAsPhrase) {
    promptText = 'Please enter the phrase you\'d like to highlight:';
  } else {
    promptText =
        'Please enter the words you\'d like to highlight, separated by spaces:';
  }
  if (isPrompt) defaultSearchText = prompt(promptText, defaultSearchText);

  if (!defaultSearchText) {
    alert('No search terms were entered. Exiting function.');
    return false;
  }

  return highlightSearchTerms(
      defaultSearchText, treatAsPhrase, true, highlightStartTag,
      highlightEndTag);
}
<input style="color:Black" type="button" value="Highlight Text" onclick="return searchPrompt('JavaScript',true,false)" />

你可以访问此链接以观看此代码的工作,也可以使用它。当你运行上面的代码时,将出现以下按钮:

单击此按钮后,将出现提示。你可以输入所有需要在提示中高亮显示的单词,为你提供所需的输出。

输出:


在 JavaScript 中使用 Mark 标记方法高亮显示文本

你可以用来高亮显示文本的另一种方法是 mark 标签。如果你在标记标签内包围任何文本,浏览器将自动以醒目的黄色高亮显示它。

This word is <mark>highlighted</mark>

这将使高亮显示搜索的文本成为一项非常简单的任务。这个程序是在 JSfiddle 中实现的。

在纯 HTML、CSS 和 JavaScript 中,该软件接受输入文本并高亮显示你搜索的文本,并从你将用作输入文本的段落中标记出来。

以下是如何实施此程序的示例:

  • 获取搜索到的文本。
  • 获取整个文本。
  • searched_text 替换 searched_text 的所有实例
  • 将新文本设置为 innerHTML.

例子:

<h1>
    Search and Mark
</h1>

<input type="text" id="search"/>
<button onClick="search(id)" id="button">
Highlight
</button>

<p id="text">
Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications.

Most websites use it for client-side page behavior, and all major web browsers have a dedicated JavaScript engine to execute it. (This excerpt was taken from Wikipedia)
</p>
function search(e) {
  let searched = document.getElementById('search').value.trim();
  if (searched !== '') {
    let text = document.getElementById('text').innerHTML;
    let re = new RegExp(searched, 'g');  // search for all instances
    let newText = text.replace(re, `<mark>${searched}</mark>`);
    document.getElementById('text').innerHTML = newText;
  }
}

单击此链接以显示上面给出的代码段的工作。

输出:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便