
유튜브 수코딩이라는 채널의 강의를 보고 참고해서 타이핑(Typing)하는 효과를 만들어 봤습니다. 마이클 조던같은 NBA 전설적인 스타들의 이름이 화면에 타이핑 하듯이 나타납니다.
<!DOCTYPE html>
<style>
#typingBox {
position: relative;
height: 300px;
}
#typing {
position: absolute; left: 50%; top: 50%;
transform: translate(-50%, -50%); width: 80%;
font-size: 40px; font-weight: bold;
font-family: sans-serif;
text-align: center; word-break: break-all;
background: inherit;
}
#typing::after {
content: "";
width: 0.1em; height: 1em;
transform: translateY(10%);
margin-left: 0.1em;
display: inline-block;
background: inherit;
}
.caret::after {
filter: invert();
}
</style>
<div id="typingBox">
<span id="typing" class="caret"></span>
</div>
<script>
var nameObj = {
list: [
{ name: "Michael Jordan", back: "red", front: "black" },
{ name: "Larry Bird", back: "green", front: "white" },
{ name: "Kobe Bryant", back: "yellow", front: "darkviolet" },
{ name: "LeBron James", back: "black", front: "purple" },
{ name: "Stephen Curry", back: "gold", front: "blue" },
],
index: -1,
change: function() {
while(true) {
var newIndex = Math.floor(Math.random() * this.list.length);
if (this.index != newIndex) {
this.index = newIndex;
break;
}
}
},
getFront: function() { return this.list[this.index].front; },
getBack: function() { return this.list[this.index].back; },
getName: function() { return this.list[this.index].name; }
};
var typingElem = document.getElementById("typing");
var restName = null;
function changeName() {
nameObj.change();
typingElem.parentElement.style.backgroundColor = nameObj.getBack();
typingElem.style.color = nameObj.getFront();
typingElem.innerHTML = "";
restName = nameObj.getName();
setTimeout(typing, 500);
}
function typing() {
if (restName) {
typingElem.innerHTML += restName[0];
restName = restName.slice(1);
setTimeout(typing, 120);
}
else {
setTimeout(changeName, 1000);
}
}
function caretBlink() {
typingElem.classList.toggle("caret");
}
changeName();
setInterval(caretBlink, 400);
</script>