将一个单词拆分为一个div,每个字母又一个自己的div

时间:2019-10-10 19:00:55

标签: javascript

我正在尝试创建一个很酷的动画,但为此,我需要将存在空格的单词拆分为自己的div,这样看起来像这样:

<h1 class="fancy-word">
<span class="word">
  <span class="word__inner">A</span>
  <span class="word__inner">b</span>
  <span class="word__inner">o</span>
  <span class="word__inner">u</span>
  <span class="word__inner">t</span>
</span>

<span class="word">
  <span class="word__inner">m</span>
  <span class="word__inner">y</span>
</span>

<span class="word">
  <span class="word__inner">s</span>
  <span class="word__inner">i</span>
  <span class="word__inner">t</span>
  <span class="word__inner">e</span>
</span>
</h1>

到目前为止,我只能对整个单词进行“分组”。

var h1 = document.querySelector(".fancy-word"); //  h1
var text = h1.textContent.split("");                 // Content into array

var result = ""; // Will hold output

// Loop
text.forEach(function(char){
  result += (char.trim() === "") ? "" : "<span>" + char + "</span>";
});

h1.innerHTML = result;  

console.log(h1.outerHTML); 
<h1 class="fancy-word">About my site</h1>

我如何才能最好地做到这一点?

4 个答案:

答案 0 :(得分:1)

  1. 在空格处拆分以获取每个单词的数组。
  2. 使用没有分隔符的另一个拆分来映射该数组,以使每个数组条目成为每个字母的另一个数组。
  3. 映射内部数组以使用word_inner类将每个字母包裹在一个跨度中,然后映射外部数组以将每个生成的拆分词将其包装到一个具有词类的跨度中。

示例:

const h1 = document.querySelector('h1');
let words = h1.textContent.split(' ');
words = words.map(word => {
  let letters = word.split('');
  letters = letters.map(letter => `<span class="word_inner">${letter}</span>`);
  return letters.join('');
});
words = words.map(word => `<span class="word">${word}</span>`);
h1.innerHTML = words.join(' ');
console.log(h1.innerHTML);
<h1>ABOUT MY SITE</h1>

答案 1 :(得分:1)

这就是我要做的:

// create and configure elements we're going to re-use
const wordTemplate = document.createElement('span');
const charTemplate = wordTemplate.cloneNode(false);

wordTemplate.classList.add('word');
charTemplate.classList.add('word__inner');

coolSplitString('About my site');

function coolSplitString(str) {
  const words = str.split(' '); // split the string into words

  words.forEach((word) => {
    const wordSpan = wordTemplate.cloneNode(false); // create a word-container

    word.split('').forEach((char) => { // split the word into letters
      const charSpan = charTemplate.cloneNode(false); // create a letter-container
      charSpan.textContent = char; // add the letter as text
      wordSpan.append(charSpan); // add letter-container to word-container
    });

    document.body.append(wordSpan); // add word-container to document
    console.log(wordSpan.innerHTML);
  });
}

答案 2 :(得分:1)

在将字符串拆分为单个字符之前,将其拆分为单词数组。然后,您可以遍历每个单词,遍历每个单词中的字符,然后在这之间做您需要做的事情。

在这里的示例中,我将事情分为几个函数来分解。此示例还包括有条件地将css类添加到包装元素的功能。

此处的基本方法:

  1. 将文本分成单词数组。
  2. 环绕words数组,为每个单词添加一个包装,然后将其传递给包装每个字符的函数。
  3. 将结果推入新数组
  4. 返回数组的联接版本以创建新字符串。

快速说明:我在这里使用了es6语法,因此,如果您不想使用模板文字,可以将其替换为字符串。

/**
 * Add wrappers to individual characters in a word
 * @method addWrappers
 * @param  {String}    word    - The word to be processed
 * @param  {String}    tag     - The HTML tag to be used for the wrappers
 * @param  {String}    classes - OPTIONAL - Any CSS classes to be applied
 * @return {String}            - Wrapped chracters as a new string.
 */
function addWrappers(word, tag, classes) {
  // Split into individual characters.
  const chars = word.split('');
  
  // The array the newly wrapped 
  // characters will be added to.
  const wrappedChars = [];
  
  // The loop
  chars.forEach(function(char) {
    // Check if any classes were passed.
    // If so add them, else just use a basic tag.
    const openTag = classes ? `${tag} class="${classes}"` : tag;
    wrappedChars.push(`<${openTag}>${char}</${tag}>`);
  });
  return wrappedChars.join('');
}

// A basic implementation.  
function initBasic() {
  const element = document.querySelector('.fancy-word')
  const text = element.textContent;
  
  // Split the string into words
  const words = text.split(' ');
  
  // Our array of processed words
  const newContent = [];
  
  // The main loop
  words.forEach(function(word) {
    newContent.push(`<span class="word">${addWrappers(word, 'span', 'word__inner')}</span>`);
  });
  // Add a space to keep the words looking 
  // right wirhout styling, but you can easily just
  // leave it out and use margins or padding 
  // to create the desired effect.
  element.innerHTML = newContent.join(' ');
  console.log(element.outerHTML);
}

initBasic();
<h1 class="fancy-word">About my site</h1>

没有模板文字的示例:

/**
 * Add wrappers to individual characters in a word
 * @method addWrappers
 * @param  {String}    word    - The word to be processed
 * @param  {String}    tag     - The HTML tag to be used for the wrappers
 * @param  {String}    classes - OPTIONAL - Any CSS classes to be applied
 */
function addWrappers(word, tag, classes) {
 const chars = word.split('')
  const wrappedChars = [];
  chars.forEach(function(char) {
    const openTag = classes ? tag + ' class="' + classes + '"' : tag;
    wrappedChars.push('<' + openTag + '>' + char + '</' + char + '>')
  });
  return wrappedChars.join('');
}

function initBasic() {
  const element = document.querySelector('.fancy-word')
  const text = element.textContent;
  
  const words = text.split(' ');
  const newContent = [];
  
  words.forEach(function(word) {
    newContent.push('<span class="word">' + addWrappers(word, 'span', 'word__inner') + '</span>');
  });
  element.innerHTML = newContent.join(' ');
  console.log(element.outerHTML);
}

答案 3 :(得分:0)

您正在寻找类似的东西吗?

var h1 = document.querySelector(".fancy-word"); //  h1
var text = h1.textContent.split(" ");                 // Content into array

var result = ""; // Will hold output

// Loop
text.forEach(function(word){
  innerResult = "";
  word.split("").forEach((letter) => {
      innerResult += (letter.trim() === "") ? "" : "<span>" + letter + "</span>";
  })
  result += "<span>" + innerResult + "</span>";
});

h1.innerHTML = result;  

console.log(h1.outerHTML); 
<h1 class="fancy-word">About my site</h1>