如何随机更改HTML文档正文中的每个字符?

时间:2017-03-07 20:17:12

标签: javascript dom

AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

我想创建一个函数,它将占用#contents中的每个字符并随机更改它。这些变化不应该影响风格。该函数应用于click事件的#randomText。我怎么能用纯JavaScript编写呢?我在这里写了一个非常糟糕的功能,无法正确完成工作。请帮忙......

2 个答案:

答案 0 :(得分:-1)

这应该有效,它使用treewalker api来快速查找所有文本节点:

编辑:添加了重置示例。 编辑:排除的字符不在字母表中。

function getAllTextNodes(node){
  var currentNode, nodes = [];
  var treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, 
    { acceptNode: function(node) {
      if(/\S/.test(node.data)) return NodeFilter.FILTER_ACCEPT;
    }}, false);
  while(currentNode = treeWalker.nextNode()) nodes.push(currentNode);
  return nodes;
}

function randomIndex(array) {
    return Math.floor(Math.random() * array.length);
}

function createRandomChar(char) {
  var lower = "abcdefghijklmnopqrstuvwxyz";
  var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var number = "0123456789";
  if((lower+upper+number).indexOf(char) < 0) return char;
  if(!isNaN(parseInt(char))) return number[randomIndex(number)];
  if(char === char.toLowerCase()) return lower[randomIndex(lower)];
  if(char === char.toUpperCase()) return upper[randomIndex(upper)];
  return char;
}

function randomizeContent(selector) {
    var element = document.querySelector(selector);
    var textNodes = getAllTextNodes(element);
    textNodes.forEach(function(node) {   
      node.textContent = node.textContent.split('').map(function(char) {
        return createRandomChar(char);
      }).join('');
    });
}

// example code
function reset(nodes, originalNodes) {
  nodes.forEach(function(node, index) {
    node.textContent = originalNodes[index] && originalNodes[index].textContent
  });
}

var contentSelector = '#contents';
var contentElement = document.querySelector(contentSelector);
var originalNodes = getAllTextNodes(contentElement).map(function(node) {
  return node.cloneNode();
});

document.querySelector('#randomText').addEventListener('click', function(e) {
  randomizeContent(contentSelector);
});

document.querySelector('#resetRandomText').addEventListener('click', function(e) {
  reset(getAllTextNodes(contentElement), originalNodes);
});
<div id="contents">
    <h1>Article I</h1>
    <section id="sectionOne">
        <p>Hello World</p>
        <ul>
            <li><a href="#">Black world</a></li>
            <li><a href="#">White world</a></li>
            <li><a href="#">666 world</a></li>
        </ul>
    </section>
    <section>
      <p>
      A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy, my dear friend, so absorbed in the exquisite sense of mere tranquil existence, that I neglect my talents.
      </p>
    </section>
</div>
<button id="randomText">Random Text</button>
<button id="resetRandomText">reset</button>

答案 1 :(得分:-1)

(function(){
      var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var unfiltered_nodes = document.querySelectorAll('#contents *');
      var nodes = [].filter.call(unfiltered_nodes, function(n){ return !n.children.length; });
      var btn = document.querySelector('#randomText');
      btn.onclick = randomize;
      
      function randomize(){
        for(var i = nodes.length-1; i > -1; i--){
            var word = nodes[i].innerText;
            for(var j = word.length-1; j > -1; j--){
              var random_char = getRandomChar();
              word = word.replace(word[j], random_char);
            }
            nodes[i].innerText = word;
          }    
      }
        
      function getRandomChar(){
          var len = chars.length-1;
          var index = Math.floor(Math.random() * (len));
          return chars[index];
      }
    })();
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body style='padding:5px;'>
  <div id="contents">
    <h1>Article I</h1>
    <section id="sectionOne">
        <p>Hello World</p>
        <ul>
            <li><a href="#">Black world</a></li>
            <li><a href="#">White world</a></li>
            <li><a href="#">666 world</a></li>
        </ul>
    </section>
</div>
<button id="randomText">Random Text</button>
</body>
</html>