我想创建一个不基于 textarea 的简单 ascii 动画。这是我的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Simple Animation</title>
<style type="text/css">
body { white-space: pre; font: 16px monospace; }
#animation { position: relative; width: 500px; height: 332px; }
#animation .image { position: absolute; left: 0; top: 0; }
.red { color: #ee0000; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" >
$(function(){
$('#animation div.image:gt(0)').hide();
setInterval(function(){
$('#animation :first-child').hide()
.next('div.image').show()
.end().appendTo('#animation');},
500);
});
</script>
</head>
<body>
<div id="animation">
<div class="image">
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
</div>
<div class="image">
YYYYYYYYYYYYYYYYYY
YYYYYYYYYYYYYYYYYY
YYYYYYYYYYYYYYYYYY
</div>
<div class="image">
ZZZZZZZZZZZZZZZZZZ
ZZZZZZZZZZZZZZZZZZ
ZZZZZZZZZZZZZZZZZZ
</div>
</div>
</body>
</html>
它完全按照我想要的方式工作。但是,当我尝试添加一些颜色时,问题就开始了。如果我将 X 的第一行更改为
<span class="red">XXXXXXXXXXXXXXXXXX</span>
动画变得很疯狂,有些线条出现了,有些没有,有些是彩色的,有些还是黑色的等等。当我尝试添加更多颜色时,情况变得更糟。
我的问题是:为什么会发生这种情况以及如何解决?我不是 javascript 专业人士,我怀疑这可能是选择器的问题,但我无法自己修复它。谢谢!
最佳答案
原因是使用:first-child
而不是:first
;对于没有子元素的元素,它可以工作,如果它们有子元素,则会破坏您的代码。
虽然 :first 仅匹配单个元素,但 :first-child 选择器可以匹配多个元素:每个父元素一个。
所以这样:
$('#animation :first-child').hide()
将选择两个元素而不是一个(两个嵌套的子元素)并且您的代码会打断它的动画;尝试将 console.log 放入您的 setInterval 中,您会看到不同之处。
来自文档:
The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.
关于javascript - 添加颜色后,简单的基于 jQuery 的 ascii 动画崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813060/