代码之家  ›  专栏  ›  技术社区  ›  james_womack

用JavaScript高亮显示网页上的每个单词,一次一个

  •  2
  • james_womack  · 技术社区  · 16 年前

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

    4 回复  |  直到 16 年前
        1
  •  2
  •   mkoryak    16 年前

    您将需要获取某个内容的innerHTML,然后在空间上拆分它,然后用不同的类在每个单词周围环绕一个跨度,并将它放回文本的位置。

    用css把它们涂成不同的颜色。

    我不知道你打算如何强调他们“一次一个”。那是动画还是什么?

        2
  •  0
  •   PPShein    16 年前

    很简单。

    <script type="text/javascript">
    var str="ppshein is coldfusion developer.!";
    document.write(str.replace("coldfusion", "<span style='background:orange;'>coldfusion8</span>"));
    </script> 
    
        3
  •  0
  •   Community Mohan Dere    9 年前

    这实际上有点取决于文本。如果您想替换的区域中有标记,那么innerHTML上的regex替换就不能很好地工作,我不怀疑。

    像这样:

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

    另一种方法是在DOM中的文本节点上迭代。如果你不是针对IE,你可以使用 TreeWalker other ways to iterate text nodes

    然后,我们的想法是迭代文本节点,对节点数据执行regex拆分,并将每个子节点包装在一个带有背景的跨度中以高亮显示。

    这里有一个相当仓促的例子,但它应该给你的想法。

    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);
    }

        4
  •  0
  •   james_womack    16 年前

    这是我的工作但是 实现一次突出显示一个单词以及在到达每行的最后一个单词时滚动的代码:

        <!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>
    
    推荐文章