javascript - 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>
解决方案
您的代码在字符串中搜索空格以使用strText.split(" ");
. 空格然后丢失。要恢复它们,请在使用添加的跨度重构字符串时将它们添加text.innerHTML += "<span>" + splitText[i] + "</span> ";
回来text.innerHTML += "<span>" + splitText[i] + "</span> ";
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>
推荐阅读
- ios - 在 IOS 中用自定义 SFSafariViewController 替换 AppAuth
- laravel - 调用未定义的方法 Illuminate\Container\Container::getLocale() | 拉拉维尔 8
- grpc-web - gRPC-js + Angular ngx-grpc - Stream 在收到 4 条消息后停止接收消息
- r - 将宽数据帧重塑为长格式
- php - 比较数组值并选择特定的值
- linux - X11 窗口失去 Qt 窗口的活动状态
- keycloak - 我可以将“主题提示”传递给 Keycloak,例如 kc_idp_hint
- ruby-on-rails - 在 Elasticsearch 索引更新完成之前查询返回旧数据
- angular - 角度路由延迟加载不适用于书签路线
- azure - 使用 LogicApp 占用 40 分钟的并行性三重 Foreach 执行缓慢?