我正在try 使用background-position创建一个平滑的动画来模拟缓慢移动的背景图像.虽然动画在Chrome和Edge中按预期运行,但在Firefox中,动画为isn't running smooth;图像的背景位置以小 skip 方式移动.

如果您使用Firefox以及Chrome或Edge打开this link,您可以看到其中的区别.

我的html代码:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <div class="img-background-horizontal"></div>
  </body>
</html>

css代码:

body {
  padding: 0;
  margin: 0;
}

.img-background-horizontal {
  background-image: url("https://cdn.pixabay.com/photo/2020/12/18/15/29/mountains-5842346_1280.jpg");
  background-size: 105vw auto;
  background-position: 0% 0%;
  height: 100vh;
  width: 100vw;
  animation: horizontalMove 50s infinite;
  animation-timing-function: ease;
}

@keyframes horizontalMove {
  0% {
    background-position: 0% 0%;
  }
  50% {
    background-position: 100% 20%;
  }
  100% {
    background-position: 0% 0%;
  }
}

我试图通过将animation-timing-function更改为例如cubic-bezier来解决这个问题,但问题仍然存在.我怀疑当动画运行速度非常慢时,Firefox中就会出现这个问题.当我将animation-duration减少到几秒时,动画运行得更快并且看起来很流畅.然而,调整这个参数对我来说不是一个可行的解决方案.

我可以采取哪些措施来解决这个问题?

推荐答案

Firefox似乎能够流畅地过渡元素.

此片段给出了一个示例,其中before p伪元素上的backgrouund,该元素比实际的dis更大,并且是动画的内容.

注意:背景大小设置为覆盖并居中,因此在任何视图大小上看起来都可以.

您需要更改%转换以满足您的要求.

body {
  padding: 0;
  margin: 0;
}

.img-background-horizontal {
  height: 100vh;
  width: 100vw;
  position: relative;
  overflow: hidden;
}

.img-background-horizontal::before {
  content: '';
  background-image: url("https://cdn.pixabay.com/photo/2020/12/18/15/29/mountains-5842346_1280.jpg");
  background-position: 0% 0%;
  height: 110vh;
  width: 110vw;
  animation: horizontalMove 50s infinite;
  animation-timing-function: ease;
  position: absolute;
  top: -2.5vh;
  left: -2.5vw;
  background-size: cover;
  background-position: center center;
  overflow: hidden;
}

@keyframes horizontalMove {
  0%,
  100% {
    transform: translate(0, 0)
  }
  50% {
    transform: translate(-5%, 2%);
  }
}
<div class="img-background-horizontal"></div>

Css相关问答推荐

如果父元素跨越所有网格列,子元素是否可以与网格一起工作?

Tailwind CSS group-hover不适用于自定义前置码

为什么图像加载请求没有显示在我的网络请求中?

如何将CSS Paint API与Reaction一起使用

单独.css文件中的样式不适用于Angular 元件

如何使用 tailwind css 修复滚动条始终位于底部?

如何使用 :has() 父 Select 器 Select 父元素的子元素,在父元素和子元素之间没有中间层的情况下?

如何为 React Native switch 组件创建标签?

使用 React 和 Flexbox 文本溢出框外

使用 :checked 显示隐藏的侧面板

Nativewind 的某些样式不适用于本机 (Android),但它们适用于网络

如何给三角形添加渐变?

flex 容器中的两个滚动块

包含tailwind 中固定纵横比框的内容

如何倾斜元素但保持文本正常(未倾斜)

使用@font-face 使用多种自定义字体?

CSS设置宽度以填充剩余区域的百分比

当子元素水平溢出时,为什么忽略父元素的右填充?

在 react-native 中使用 flex 使项目粘在底部

100% 高度减go 标题?