逐字显示文本但保留html格式

时间:2017-06-06 14:42:05

标签: javascript html

我需要我的文本保留一些html格式标签,例如更改文本的颜色,并显示放置在我的文本中的一些图形图标。我的代码从现有的隐藏段落中取出文本,将段落空白,取消隐藏,然后逐字逐句显示。

        var NextHighlight = HighlightsTop.find('.newhidden').first().closest('p'); // Find the paragraph.
        // Put the text from this highlight paragraph into a variable and remove it from the paragraph, so that we can put it back letter-by-letter below.
        var HighlightText = NextHighlight.html();
        NextHighlight.html("");
        NextHighlight.removeClass('newhidden');

        // Add the text back in, letter by letter.
        showText(NextHighlight, HighlightText, 0, 5);    

....

    // The letter-by-letter function.
    var showText = function (target, message, index, interval) {    
    if (index < message.length) { 
        $(target).append(message[index++]); 
        setTimeout(function () { showText(target, message, index, interval); }, interval); 
        } 
    }

问题是html标签现在只是在行中显示为直文。如果我在元素中将'html'更改为'text',它不显示标签,但我也没有得到格式。

编辑 - 更新以下....

使用下面的答案更新后,我的代码现在看起来像这样。我应该指出,当用户点击按钮时会发生这种情况,因此我从按钮点击开始添加代码。也许在某个地方有一个我无法看到的错误,因为当我现在点击按钮时,我什么也得不到。我也没有在控制台中看到任何错误,想知道我是否错过了一个;某处...

$(document).on('click', '.highlight_button',
    function () {
        var MatchReportTop = $(this).closest('.match_div'); 
        var HighlightsTop = $(this).closest('.highlights');
        var NextHighlight = $('.newhidden').first().closest('p'), HighlightTextNodes = [];

        // recursively get the text nodes
        (function recursiveGetTextNodes(node) {
          if(node.nodeType === 3) {
            // we're a text node? great, store it.  We'll store a clone and the original so we don't lose our place.
            HighlightTextNodes.push({
              active: node,
              ref: node.cloneNode()
            });
            // clear out the original.
            node.textContent = '';
          } else {
            // no text node.  go deeper.
            for(var i = 0, len = node.childNodes.length; i < len; i++) {
              recursiveGetTextNodes(node.childNodes[i]);
            }
          }
        })(NextHighlight.get(0))

        // Add the text back in, letter by letter.
        showText(HighlightTextNodes, 5);

        if (NextHighlight.hasClass('FullTime')) {
            CompleteReveal(MatchReportTop);
        }
}); 

// The letter-by-letter function.
function showText(target, interval) {
  // to know what we're currently working on, we need to filter
  // the text nodes by a check to see if they are already fully
  // "typed" out.  If the content doesn't match, keep it.  Also,
  // `shift()` off the first one.  That's the one we'll edit
  // this go around.
  var current = target.filter(function(a){
    return a.active.textContent != a.ref.textContent;
  }).shift();

  // if we have a node to work with, the process is not
  // completed. Once `current` is false, we know we've completed
  // the process.
  if (current) { 
    // grab the reference node's text up to the active node's
    // length +1 to get the current text plus one letter.
    current.active.textContent = current.ref.textContent.substr(0,current.active.textContent.length + 1);
    // rinse and repeat.
    setTimeout(function () {
      showText(target, interval);
    }, interval); 
  }
}

1 个答案:

答案 0 :(得分:1)

因此,您希望逐步显示文本,但必须保留HTML。您可以剥离标签并重新应用它们。在解析文本时可以忽略标记,只需将它们全部粘贴即可。这些是首先想到的几种选择,但我有点不喜欢它们。

如果您重新考虑问题,可能会有更好的解决方案。您可以仅定位文本节点,并以增量方式显示这些文本节点中的每个字母。这是我重新思考之后确定的计划。基本流程是这样的:

  1. 收集文本节点,存储其原始节点(仍然附加到DOM)
  2. 存储节点的克隆以供稍后参考
  3. 清空文本节点
  4. 以递归方式调用查找与引用节点
  5. 不匹配的第一个节点的定时方法
  6. 从参考节点
  7. 向该节点添加单个字母
  8. 重复,直到所有节点都与参考节点匹配
  9. // get the `newhidden`'s closest parent paragraph and prepare
    // the array that will hold all the text nodes of that paragraph
    var NextHighlight = $('.newhidden').first().closest('p'), HighlightTextNodes = [];
    
    // recursively get the text nodes
    (function recursiveGetTextNodes(node) {
      if(node.nodeType === 3) {
        // we're a text node? great, store it.  We'll store a clone
        // and the original so we don't lose our place.
        HighlightTextNodes.push({
          active: node,
          ref: node.cloneNode()
        });
        // clear out the original.
        node.textContent = '';
      } else {
        // no text node.  go deeper.
        for(var i = 0, len = node.childNodes.length; i < len; i++) {
          recursiveGetTextNodes(node.childNodes[i]);
        }
      }
    })(NextHighlight.get(0))
    
    // Add the text back in, letter by letter.
    showText(HighlightTextNodes, 5);
    
    // The letter-by-letter function.
    function showText(target, interval) {
      // to know what we're currently working on, we need to filter
      // the text nodes by a check to see if they are already fully
      // "typed" out.  If the content doesn't match, keep it.  Also,
      // `shift()` off the first one.  That's the one we'll edit
      // this go around.
      var current = target.filter(function(a){
        return a.active.textContent != a.ref.textContent;
      }).shift();
      
      // if we have a node to work with, the process is not
      // completed. Once `current` is falsy, we know we've completed
      // the process.
      if (current) { 
        // grab the reference node's text up to the active node's
        // length +1 to get the current text plus one letter.
        current.active.textContent = current.ref.textContent.substr(0,current.active.textContent.length + 1);
        // rinse and repeat.
        setTimeout(function () {
          showText(target, interval);
        }, interval); 
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, impedit <strong class="newhidden">labore <span>test</span> architecto</strong> quasi, possimus hic velit. Quibusdam quisquam illum quae doloremque, quis iste consequatur vero quaerat molestias doloribus dicta facilis.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas iusto laborum hic optio aliquam, adipisci a, dolore rem dolores harum voluptas cum! Similique, velit, commodi. Vero molestias, nobis ducimus nemo.</p>