首页 > 解决方案 > H1 html标记似乎没有空格

问题描述

我是 HTML 的新手,我正在尝试一些简单的动画。在教程的帮助下,我可以做一些简单的动画,但不知何故,尽管放置了空格,但我的 h1 类文本似乎没有空格。基于 w3school 代码编辑器,在尝试在单词之间创建空格时,只需在 h1 类中添加空格就足够了。

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_class

const text = document.querySelector(".hello");
const strText = text.textContent;
const splitText = strText.split(" ");

text.textContent = "";

for (let i = 0; i < splitText.length; i++) {
  text.innerHTML += "<span>" + splitText[i] + "</span>";
}

let char = 0;
let timer = setInterval(onTick, 50);

function onTick() {
  const span = text.querySelectorAll('span')[char];
  span.classList.add('fade');
  char++;
  if (char === splitText.length) {
    complete();
    return;
  }
}

function complete() {
  clearInterval(timer);
  timer = null;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: black;
}

h1 {
  color: white;
  font-size: 4rem;
  font-family: sans-serif;
}

span {
  opacity: 0;
  transition: all 1s ease;
  transform: translateY(50px);
  display: inline-block;
}

span.fade {
  opacity: 1;
  color: red;
  transform: translateY(0px);
}
<h1 class="hello">Testing 1 2 3</h1>

标签: javascripthtmlcss

解决方案


您的代码在字符串中搜索空格以使用strText.split(" ");. 空格然后丢失。要恢复它们,请在使用添加的跨度重构字符串时将它们添加text.innerHTML += "<span>" + splitText[i] + "</span> ";回来text.innerHTML += "<span>" + splitText[i] + "</span>&nbsp;";

const text = document.querySelector(".hello");
const strText = text.textContent;
const splitText = strText.split(" ");

text.textContent = "";

for (let i = 0; i < splitText.length; i++) {
  text.innerHTML += "<span>" + splitText[i] + "</span> ";
}

let char = 0;
let timer = setInterval(onTick, 50);

function onTick() {
  const span = text.querySelectorAll('span')[char];
  span.classList.add('fade');
  char++;
  if (char === splitText.length) {
    complete();
    return;
  }
}

function complete() {
  clearInterval(timer);
  timer = null;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: black;
}

h1 {
  color: white;
  font-size: 4rem;
  font-family: sans-serif;
}

span {
  opacity: 0;
  transition: all 1s ease;
  transform: translateY(50px);
  display: inline-block;
}

span.fade {
  opacity: 1;
  color: red;
  transform: translateY(0px);
}
<h1 class="hello">Testing 1 2 3</h1>


推荐阅读