使用 JavaScript 一次突出显示网页上的每个单词

发布于 2024-09-13 00:45:24 字数 132 浏览 8 评论 0原文

一次一个地突出显示页面上每个单词的最佳方式是什么?我认为这些单词应该分解成一个数组并以这种方式迭代,但是最好的方法是什么?

我已经知道如何执行字符串替换和设置单个元素的样式,技巧是以最有效的方式对页面上的每个单词执行此操作,一次一个。

What's the best way to visually highlight each word on the page, one at a time? I figure that the words should be broken up into an array and iterated over that way, but what's the best way to do so?

I already know how to perform string replacements and style individual elements, the trick is to do this on each word on the page, one at a time, in the most efficient manner.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

2024-09-20 00:45:24

您需要获取某些内容的innerHTML,然后将其分割到空间中,然后用不同的类将每个单词包裹在一个跨度中,并将其设置回文本的位置。

使用 css 给它们设置不同的颜色或其他东西。

我不确定你打算如何“一次一个”地突出显示它们。这涉及动画什么的吗?

you will need to grab the innerHTML of something, then split it over space, then wrap a span around each word with different classes, and set it back in place of text.

use css to color these differently or something.

i am not sure how you plan to highlight them "one at a time". does that involve an animation or something?

放肆 2024-09-20 00:45:24

这很简单。

<script type="text/javascript">
var str="ppshein is coldfusion developer.!";
document.write(str.replace("coldfusion", "<span style='background:orange;'>coldfusion8</span>"));
</script> 

It's simple.

<script type="text/javascript">
var str="ppshein is coldfusion developer.!";
document.write(str.replace("coldfusion", "<span style='background:orange;'>coldfusion8</span>"));
</script> 
记忆で 2024-09-20 00:45:24

它实际上取决于文本。如果您想要替换的区域内有标签,那么我不怀疑innerHTML 上的正则表达式替换效果不会那么好。

像这样:

<p><strong>F</strong>irst letter of paragraph</p>

另一种方法是迭代 DOM 中的文本节点。如果您的目标不是 IE,则可以使用 TreeWalker 轻松获取集合按文档顺序排列的文本节点。如果您需要以 IE 为目标,这似乎是 迭代文本的其他方法的一个很好的总结节点

然后,想法是迭代文本节点,对节点数据进行正则表达式分割,并将每个子节点包装在带有背景的跨度中以突出显示。

这是一个相当仓促编写的示例,但它应该可以让您有所了解。

var iterator = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false),
 template = document.createElement('span'),
 span,
 node,
 text,
 newNode;

template.style.backgroundColor = 'yellow';

while ((node = iterator.nextNode())) {
 text = node.data.split(/\b/g);

 for (var i = 0, len = text.length; i < len; i++) {
  newNode = document.createTextNode(text[i]);
  if (text[i].search(/\w+/) >= 0) {
   span = template.cloneNode(false);
   span.appendChild(newNode);
   node.parentNode.insertBefore(span, node);
  } else {
   node.parentNode.insertBefore(newNode, node);
  }
  iterator.currentNode = newNode;
 }
 node.parentNode.removeChild(node);
}

它不会是最快的可用方法,但它应该比innerHTML 上的正则表达式替换更准确。修改循环以使用 window.setTimeout 来设置突出显示动画也不是那么困难。

It actually kind of depends on the text. If you've got tags within the area you're wanting to replace, the regex replace on the innerHTML won't work that well I don't suspect.

Something like this:

<p><strong>F</strong>irst letter of paragraph</p>

The alternative is to iterate over text nodes within the DOM. If you're not targeting IE, you can use the TreeWalker to easily get a collection of text nodes in document order. If you need to target IE, this seems to be a good summary of other ways to iterate text nodes

Then the idea would be to iterate over the text nodes, do the regex split on the node data and wrap each child node in a span with background to highlight.

Here's a fairly hastily written example, but it should give you the idea.

var iterator = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false),
 template = document.createElement('span'),
 span,
 node,
 text,
 newNode;

template.style.backgroundColor = 'yellow';

while ((node = iterator.nextNode())) {
 text = node.data.split(/\b/g);

 for (var i = 0, len = text.length; i < len; i++) {
  newNode = document.createTextNode(text[i]);
  if (text[i].search(/\w+/) >= 0) {
   span = template.cloneNode(false);
   span.appendChild(newNode);
   node.parentNode.insertBefore(span, node);
  } else {
   node.parentNode.insertBefore(newNode, node);
  }
  iterator.currentNode = newNode;
 }
 node.parentNode.removeChild(node);
}

It won't be the fastest method available, but it should be more accurate than a regex replace on the innerHTML. It's also not that difficult to modify the loop to use window.setTimeout to animate the highlighting.

衣神在巴黎 2024-09-20 00:45:24

这是我的工作但未完善的代码,它可以一次突出显示每个单词,并在到达每行中的最后一个单词时滚动:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title></title>
    <style type="text/css">
    span.highlight {background-color:red;}
    </style>
    <script>
    var height;
    var width;
    var spans = document.getElementsByTagName("span");
    var i = 0;
    var timePerChar = 100;

    function getPositionOfElement(el) {
        var elw =  el.offsetWidth;
        var elh =  el.offsetHeight;
        // yay readability
        for (var lx=0, ly=0;
             el != null;
             lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
        return {x: lx,y: ly,w: elw, h: elh};
    }

    function highlightElements() {
        //alert(spans[i].innerHTML.length);
        var highlightSpeed = timePerChar * spans[i].innerHTML.length;
        spans[i].setAttribute("class", "highlight");
        var objInfo = new Object();
        var nxtObjInfo = new Object();
        objInfo = getPositionOfElement(spans[i]);
        nxtObjInfo = getPositionOfElement(spans[i+1]);
        var amt = (objInfo.x + objInfo.w + 50);
        console.log(amt);
        console.log(width);
        if(amt >= width && objInfo.x > nxtObjInfo.x){
            console.log('SCROLL ' +objInfo.h+ ' ');
            window.scrollBy(0,objInfo.h);
        }
        setTimeout('unHighlight()', highlightSpeed);
    }

    function unHighlight (){
        spans[i].removeAttribute("class");
        i++;
        if(i < spans.length) {
            highlightElements();
        }
    }

    // This is just a namespace 
    var CIRRO = function(){ 
     return { 
      /** 
       * Initialize the page behaviors 
       */ 
      init : function() { 
       CIRRO.wrapWordsWithSpan(); 
      },   
      /** 
       * Replace the contents of each paragraph with span wrapped words 
       */ 
      wrapWordsWithSpan : function() { 
       var paragraphs = document.getElementsByTagName("p");
       //alert(paragraphs.length);
       if(!paragraphs ) return; 
       var j = 0;
       while(j < paragraphs.length) {
            // Parse the text into an array 
           var arr = paragraphs[j].innerHTML.split(" "); 
           // Generate span's for each item/word in the array 
           for( var i = 0; i < arr.length; i++ ) { 
            arr[i] = "<span>" + arr[i] + "</span>"; 
           }    
           paragraphs[j].innerHTML = arr.join(" "); 
           //alert(paragraphs[j].innerHTML); 
           j++
       }
      } 
     }; 
    }(); 
    window.onload = CIRRO.init; 
    </script>
    </head>
    <body id="body">
    <input type="button" onclick="highlightElements();" value="Get selected elements" />
    <p>Test test test test test Test test test test test Test test test test test Test 
test test test test Test test test test test Test test test test test Test test test test 
test Test test test test test Test test test test test Test test test test test Test test 
test test test Test test test test test Test test test test test Test test test test test 
Test test test test test Test test test test test Test test test test test Test test test 
test test</p>
    <script>
    var test = document.getElementById("body");
    height = (test.clientHeight + 1);
    width = (test.clientWidth + 1);
    //alert(width +' '+ height);
    </script>
    </body>

</html>

Here is my working but unrefined code that achieves highlighting each word one at a time as well as scrolling when the last word in each line is reached:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title></title>
    <style type="text/css">
    span.highlight {background-color:red;}
    </style>
    <script>
    var height;
    var width;
    var spans = document.getElementsByTagName("span");
    var i = 0;
    var timePerChar = 100;

    function getPositionOfElement(el) {
        var elw =  el.offsetWidth;
        var elh =  el.offsetHeight;
        // yay readability
        for (var lx=0, ly=0;
             el != null;
             lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
        return {x: lx,y: ly,w: elw, h: elh};
    }

    function highlightElements() {
        //alert(spans[i].innerHTML.length);
        var highlightSpeed = timePerChar * spans[i].innerHTML.length;
        spans[i].setAttribute("class", "highlight");
        var objInfo = new Object();
        var nxtObjInfo = new Object();
        objInfo = getPositionOfElement(spans[i]);
        nxtObjInfo = getPositionOfElement(spans[i+1]);
        var amt = (objInfo.x + objInfo.w + 50);
        console.log(amt);
        console.log(width);
        if(amt >= width && objInfo.x > nxtObjInfo.x){
            console.log('SCROLL ' +objInfo.h+ ' ');
            window.scrollBy(0,objInfo.h);
        }
        setTimeout('unHighlight()', highlightSpeed);
    }

    function unHighlight (){
        spans[i].removeAttribute("class");
        i++;
        if(i < spans.length) {
            highlightElements();
        }
    }

    // This is just a namespace 
    var CIRRO = function(){ 
     return { 
      /** 
       * Initialize the page behaviors 
       */ 
      init : function() { 
       CIRRO.wrapWordsWithSpan(); 
      },   
      /** 
       * Replace the contents of each paragraph with span wrapped words 
       */ 
      wrapWordsWithSpan : function() { 
       var paragraphs = document.getElementsByTagName("p");
       //alert(paragraphs.length);
       if(!paragraphs ) return; 
       var j = 0;
       while(j < paragraphs.length) {
            // Parse the text into an array 
           var arr = paragraphs[j].innerHTML.split(" "); 
           // Generate span's for each item/word in the array 
           for( var i = 0; i < arr.length; i++ ) { 
            arr[i] = "<span>" + arr[i] + "</span>"; 
           }    
           paragraphs[j].innerHTML = arr.join(" "); 
           //alert(paragraphs[j].innerHTML); 
           j++
       }
      } 
     }; 
    }(); 
    window.onload = CIRRO.init; 
    </script>
    </head>
    <body id="body">
    <input type="button" onclick="highlightElements();" value="Get selected elements" />
    <p>Test test test test test Test test test test test Test test test test test Test 
test test test test Test test test test test Test test test test test Test test test test 
test Test test test test test Test test test test test Test test test test test Test test 
test test test Test test test test test Test test test test test Test test test test test 
Test test test test test Test test test test test Test test test test test Test test test 
test test</p>
    <script>
    var test = document.getElementById("body");
    height = (test.clientHeight + 1);
    width = (test.clientWidth + 1);
    //alert(width +' '+ height);
    </script>
    </body>

</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文