<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
background: beige;
}
div.m {
position: relative;
width: 1920px;
height: 336px;
background: url(./image/bg1.png) no-repeat;
animation: M 3S linear infinite;
background-attachment: fixed;
}
div.b {
position: absolute;
top: 50%;
width: 200px;
height: 100px;
background: url(./image/bear.png) no-repeat;
/* 元素添加多个动画 用逗号隔开 */
animation: bear .5s steps(8) infinite, move 3s linear forwards;
}
@keyframes bear {
0% {
background-position: 0 0;
}
100% {
background-position: -1600px 0;
}
}
@keyframes move {
0% {
left: 0;
}
70% {
left: 25%;
}
100% {
left: 50%;
/* margin-left: -100px; */
transform: translateX(-50%);
}
}
@keyframes M {
0% {
background-position: 0 0;
}
25% {
background-position: 25% 0;
}
50% {
background-position: 50% 0;
}
100% {
background-position: 100% 0;
}
}
</style>
<body>
<div class="m">
<div class="b"></div>
</div>
</body>
</html>
背景图片bg1.png需要设置 repeat-x横向重复;
背景图片动画 background-position的x位置要从 0 到 -3840px (3840是背景图片实际宽度), 不是100%。
代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
background: beige;
}
div.m {
position: relative;
width: 1920px;
height: 336px;
background: url(./image/bg1.png) repeat-x;
animation: M 5S linear infinite;
background-attachment: fixed;
}
div.b {
position: absolute;
top: 50%;
width: 200px;
height: 100px;
background: url(./image/bear.png) no-repeat;
/* 元素添加多个动画 用逗号隔开 */
animation: bear .5s steps(8) infinite, move 3s linear forwards;
}
@keyframes bear {
0% {
background-position: 0 0;
}
100% {
background-position: -1600px 0;
}
}
@keyframes move {
0% {
left: 0;
}
70% {
left: 25%;
}
100% {
left: 50%;
/* margin-left: -100px; */
transform: translateX(-50%);
}
}
@keyframes M {
0% {
background-position: 0 0;
}
100% {
background-position: -3840px 0;
}
}
</style>
<body>
<div class="m">
<div class="b"></div>
</div>
</body>
</html>
移动图片至结尾时因为结尾图片是直接跳转到开头的,而结尾的图片内容和开头内容不同,所以会出现一瞬间的卡顿。
解决方法:背景图片设置为横向平铺repeat-x
div.b {
position: absolute;
top: 50%;
width: 200px;
height: 100px;
background: url(./image/bear.png) repeat-x;
/* 元素添加多个动画 用逗号隔开 */
animation: bear .5s steps(8) infinite, move 3s linear forwards;
}