繁体   English   中英

使用javascript使HTML页面中的文本变为粗体

[英]make text in html page bold with javascript

我做了什么:

 function makeBold(strings) {

            var myHTML = document.getElementsByTagName('body')[0].innerHTML;


             myHTML = myHTML.replace(strings, '<b>' + strings + '</b>');


             document.getElementsByTagName('body')[0].innerHTML = myHTML
        }

此代码仅适用于文本不包含ant标记的步伐

例如: <p class="ClassName">Some free text without any inner html elements</p>

但是对于低于此的句子,上述javascript函数未给出任何结果

例如不起作用的句子:

<p class="Aclass"><span class="char-style-override-1">Starting from here, </span><span class="char-style-override-2">text resumes after the span tag</span><span class="char-style-override-1">. again text resumes.</span></p>

我需要的

当我将上述文本传递到我的js函数中时,我需要一个使上述文本变为粗体的功能。 文字上我的意思是

Starting from here,text resumes after the span tag. again text resumes.

当我像这样调用上述jas函数时

makeBold('Starting from here,text resumes after the span tag. again text resumes.');

什么也没有发生,整个句子不会变粗体,什么也没有发生,因为js函数仅查找该字符串的出现并使其变粗,在第二个示例中,文本与html标记混合

这样,当我调用makebold函数时,上述文本将变为粗体。

Please note that i dont have the id for the <p> , what i have is a couple of random strings stored in my db and load a couple of webpages, while doing so i want to bold the sentence/text from the webpage if is matches with my passed string from db

在进行研究时,我得到了一个代码,以突出显示给js的文本。 此js函数将在html页面中选择传递给js函数的确切文本。

第二个例子也适用于此代码。 即我可以通过将其传递给函数从示例中选择确切的字符串。

function selectText(text) {
if (window.find && window.getSelection) {
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.body, 0);

    while (window.find(text)) {
        document.getElementById("button").blur();
        document.execCommand("HiliteColor", false, "yellow");
        sel.collapseToEnd();
    }
    document.designMode = "off";
} else if (document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    while (textRange.findText(text)) {
        textRange.execCommand("BackColor", false, "yellow");
        textRange.collapse(false);
    }
}

}

我尝试对其进行自定义,以便与其选择传递的文本,不如尝试使其变为粗体。 但成功了。

请帮助我完成这项工作。 我是js新手。

我终于找到了一个解决您的问题的方法,该方法可以按您希望的方式工作(即该函数采用任意子字符串,并在不影响其余字符串的情况下,将适合子字符串的所有内容标记为粗体)。 如果传递的字符串与您要修改的字符串的任何部分都不匹配,则后者保持不变。

来了( 请注意: JS部分的确很大!):

<!DOCTYPE html>
<html lang="en">
<head>
<title>Test case for making arbitrary text bold</title>
<meta charset="UTF-8">
<script type="application/javascript">
// Takes two strings and attempts to intersect them (i. e. the end of p_str1
// must match the beginning of p_str2). The index into p_str1 is returned.
// If no intersection can be found, -1 is returned.
function intersectStrings(p_str1, p_str2)
  {
var l_pos = -1;

  do
    {
    l_pos = p_str1.indexOf(p_str2[0], l_pos + 1);
    if(p_str1.substr(l_pos) == p_str2.substr(0, p_str1.length - l_pos))
// If the two substrings match, we found something. Return with the position.
      break;
    }
  while(l_pos != -1);

  return l_pos;
  }

function makeBold(p_string)
  {
var l_elem = document.getElementById('modify');
var l_html = l_elem.innerHTML;
var l_text = l_elem.innerText;
var l_aux = l_html.match(/<.+?>/g);

var l_here = l_text.indexOf(p_string);
var l_before;
var l_middle;
var l_behind;

  if(typeof(p_string) != 'string')
    throw "invalid argument";

// First of all, see whether or not we have a match at all. If no, we don't
// need to continue with this.
  if(l_here == -1)
    {
    console.error('makeBold: Could not find desired substring ' + p_string + '! Stop...');
    return;
    }

// Take the plain text and split it into three distinct parts (l_middle is of
// interest for us here).      
  l_before = l_html.slice(0, l_here);
  l_behind = l_html.slice(l_here + l_html.length);
  l_middle = l_html.slice(l_here, l_here + l_html.length);

  if(l_aux)
    {
// If we have a set of markup tags, we need to do some additional checks to
// avoid generating tag soup.
let l_target = new Array();
let l_tag;
let l_nexttag;
let l_this;
let l_endpos = 0;
let l_in_str = false;
let l_start;

    while(l_aux.length - 1)
      {
      l_tag = l_aux.shift();
      l_target.push(l_tag);
      l_nexttag = l_aux[0];
      l_endpos = l_html.indexOf(l_nexttag, 1);
      l_this = l_html.slice(l_tag.length, l_endpos);
      l_html = l_html.slice(l_endpos);
// Skip the entire rigmarole if there are two adjacent tags!
      if(l_tag.length == l_endpos)
        continue;
      if(!l_in_str)
        {
        if((l_start = l_this.indexOf(p_string)) != -1)
          {
// If we find the entire passed string in a fragment of plain text, we can
// modify that, reassemble everything and exit the loop.
          l_before = l_this.slice(0, l_start);
          l_behind = l_this.slice(l_start + p_string.length);
          l_middle = l_this.slice(l_start, l_start + p_string.length);
          l_this = l_before + '<strong>' + l_middle + '</strong>' + l_behind;
          l_target.push(l_this);
          l_target.push(l_html);
          l_html = l_target.join('');

          console.info('makeBold: The passed string fit between two tags: Done!');

          break;
          }

// Take the possibility of having to scan across fragments into account. If
// that is the case, we need to piece things together.
        if((l_start = intersectStrings(l_this, p_string)) != -1)
          {
// Once we wind up here we have a partial match. Now the piecework starts...
          l_before = l_this.slice(0, l_start);
          l_middle = l_this.slice(l_start);
          l_this = l_before + '<strong>' + l_middle + '</strong>';
          l_target.push(l_this);

          console.info('makeBold: Found starting point of bold string!');

          l_in_str = true;
          }
        else
          {
// Nothing to do: Push the unmodified string.
          l_target.push(l_this);
          }
        }
      else
        if((l_endpos = intersectStrings(p_string, l_this)) == -1)
          {
// We haven't arrived at the end position yet: Push the entire segment with
// bold markers onto the stack.
          l_this = '<strong>' + l_this + '</strong>';
          l_target.push(l_this);
          }
        else
          {
// We have an end position: Treat this fragment accordingly, wrap everything up
// and exit the loop.
          l_behind = l_this.slice(l_endpos + 1);
          l_middle = l_this.slice(0, l_endpos + 1);
          l_this = '<strong>' + l_middle + '</strong>' + l_behind;
          l_target.push(l_this);
          l_target.push(l_html);
          l_html = l_target.join('');

          console.info('makeBold: Found the end part: Done!');

          break;
          }
      }
    }
  else
    l_html = l_before + '<strong>' + l_middle + '</strong>' + l_behind;

  l_elem.innerHTML = l_html;
  }
</script>
</head>
<body>
<header><h1>Test case for making arbitrary text bold by using JavaScript</h1></header>
<main>
<p id="modify"><span class="char-style-override-1">Starting from here, </span><span class="char-style-override-2">text resumes after the span tag</span><span class="char-style-override-1">. again text resumes.</span></p>
</main>
<script type="application/javascript">
// makeBold('Starting from here, text resumes after the span tag. again text resumes.');
// makeBold('from here, text resumes');
// makeBold('resumes after the span');
makeBold('text resumes after the span tag');
</script>
</body>
</html>

不幸的是,这项工作不可能一小段就完成,因为您需要考虑需要单独处理的各种情况。 我提出的控制逻辑解决了所有这些问题。
有关详细信息,请参见我制作的JS中的注释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM