我正在尝试制作动画,以将块向右和向左移动。但是我不明白为什么它不起作用。例如,它非常适合单击事件。这是我的codepen。谢谢
const box = document.getElementsByClassName('box')[0];
document.addEventListener('keydown', function({
keyCode,
which
}) {
const keycode = keyCode ? keyCode : which;
switch (keycode) {
case (39):
box.classList.add('move-right');
box.classList.remove('move-left');
break;
case (37):
box.classList.add('move-left');
box.classList.remove('move-right');
break;
}
});
.box {
background-color: gray;
height: 100px;
width: 100px;
transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1);
transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}
.move-right {
margin-left: 400px;
}
.move-left {
margin-left: 0px;
}
<div class="box"></div>
cssCSS中有两个transition
实例
.box {
...
transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1);
transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}
如果要在左边距左边距和顶部右边距之间有不同的过渡,可以将它们组合。
.box {
...
transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1), margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}
过渡应该添加一次,这是一个有效的代码段:
const box = document.getElementsByClassName('box')[0];
document.addEventListener('keydown', function({keyCode, which}) {
const keycode = keyCode ? keyCode : which;
switch(keycode) {
case(39):
box.classList.add('move-right');
box.classList.remove('move-left');
break;
case(37):
box.classList.add('move-left');
box.classList.remove('move-right');
break;
}
});
.box {
background-color: gray;
height: 100px;
width: 100px;
transition: margin 0.5s cubic-bezier(0, .7, 0, 1);
}
.move-right {
margin-left: 400px;
}
.move-left {
margin-left: 0px;
}
<div class="box"></div>
如果您查看已编写的css
,则>
.box { background-color: gray; height: 100px; width: 100px; transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1); transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1); }
您有2个过渡属性,过渡属性被下一个覆盖,即下一个过渡
margin-top
属性。
计算样式时,这就是css规则的样子。
.box { background-color: gray; height: 100px; width: 100px; transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1); }
由于具有相同类型的键,因此在
margin-top
的此转换中,最后一个规则将获胜,而margin-left
的转换将丢失。
因此,删除第二个过渡规则或将其写为单个规则,将用逗号分隔属性。