[英]Your own style for typing text
这是使用jQuery的输入代码
我该如何使用自己的风格?
Forexmaple我想写这样的文本:
Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice too see you</strong> guys!
但是正如您所看到的,在“数据文本”中不能使用css样式和html标签。
我该怎么办?
编码:
var $typer = $('.typer'), txt = $typer.data("text"), tot = txt.length, ch = 0; (function typeIt() { if(ch > tot) return; $typer.text( txt.substring(0, ch++) ); setTimeout(typeIt, ~~(Math.random()*(200-60+1)+60)); }());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="typer" data-text="Hi! My name is Al. I will guide you trough the Setup process."></span>
您可以将data-text
设置为html
字符串,在typeIt()
调用typeIt()
.html()
替换为.text()
var $typer = $('.typer'), txt = $typer.data("text"), tot = txt.length, ch = 0; (function typeIt() { if(ch > tot) return; $typer.html( txt.substring(0, ch++) ); setTimeout(typeIt, ~~(Math.random()*(200-60+1)+60)); }());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="typer" data-text='Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice too see you</strong> guys! '></span>
另外,您可以创建一个<template>
元素,获取template
元素的.content.childNodes
。 使用template.content.childNodes
作为参数调用Array.prototype.slice.call()
。 使用Array.prototype.reduce()
迭代data-text
html
字符串的所有节点,使用带有参数""
.split()
创建当前节点.textContent
每个字符的数组。
在Promise.resolve()
.reduce()
回调中,使用Promise.resolve()
作为初始值, Promise()
构造函数要等到setTimeout
持续时间到期后,才能对子节点的当前元素执行下一个任务。
检查节点#text
节点,如果true
,将html
的$typer
使用.html(function)
,否则,如果false
店.textContent
当前节点的一个变量,调用.empty()
传递给当前节点上jQuery()
.append()
节点到$typer
.textContent
,迭代当前节点的.textContent
,在每个字符上调用.html()
以设置附加节点的.innerHTML
。
var $typer = $('.typer') , txt = $("<template>", { html: $typer.data("text") })[0].content.childNodes; Array.prototype.slice.call(txt).reduce(function(p, node) { return p.then(function() { var currentText = node.textContent.split(""); if (node.nodeType !== 3) { var curr = node; $typer.append($(node).empty()); } return currentText.reduce(function(promise, text) { return promise.then(function() { return new Promise(function(resolve) { setTimeout(function() { $(curr || $typer).html(function(_, html) { return html + text; }); resolve() }, ~~(Math.random() * (200 - 60 + 1) + 60)) }) }) }, Promise.resolve()) }) }, Promise.resolve());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <span class="typer" data-text='Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice too see you</strong> guys! '></span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.