动画字符添加到跨度

时间:2018-03-02 14:53:40

标签: javascript html css

将新字符添加到#messageCorrectrlyTyped范围时,是否可以添加效果?那么当用户输入正确的字符时?我尝试将transition: all 1s;设置为css,但它不起作用。你能救我吗?

var messageToType = document.querySelector("#messageToType");
var messageCorrectlyTyped = document.querySelector("#messageCorrectlyTyped");
var correctlyTyped = "";

document.addEventListener("keypress", function(e){
	if (messageToType.textContent.length > 0) {
		var charToPress = messageToType.textContent[0];
		var charPressed = String.fromCharCode(e.keyCode);
		if (charPressed === charToPress) {
			messageToType.textContent = messageToType.textContent.substring(1);
			messageCorrectlyTyped.textContent += charPressed;
			messageCorrectlyTyped.style.color = "green";
		} 
	}
});
#messageToType {
	font-family: "Courier New";
	font-size: 20px;
	font-weight: 700;
}

#messageCorrectlyTyped {
	font-family: "Courier New";
	font-size: 20px;
	font-weight: 700;
}

#container {
	margin: auto;
	width: 50%;
	text-align: center;
}
<!DOCTYPE html>
<html>
<head>
	<title>Test Type</title>
	<link rel="stylesheet" type="text/css" href="testType.css">
</head>
<body>
	<div id="container">
		<span id="messageCorrectlyTyped"></span><span id="messageToType">ciao</span>
	</div>

	<script type="text/javascript" src="testType.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

这是一个非常广泛的问题。

这是一个例子,告诉我它是否适合你:

&#13;
&#13;
const hider = document.querySelector('.hider');

const width = hider.offsetWidth;
hider.style.left = '0px';

const inter = setInterval(() => {
  let left = +hider.style.left.replace('px', '');
  if(left <= width) {
    hider.style.left = (left + 1) + 'px';
  } else { clearInterval(inter); }
}, 5);
&#13;
.container {
  position: relative;
}

.hider {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin-right: -1px;
  background: linear-gradient(to right, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 4%);
}
&#13;
<div class="container">
  <div class="text">Lorem Ipsum Dolor Sit Amet</div>
  <div class="hider"></div>
</div>
&#13;
&#13;
&#13;