首页 > 解决方案 > 仅使用 css 和 vanilla js 在没有插件的情况下向下滚动时从顶部显示一个按钮

问题描述

我想要一个按钮从隐藏到顶部平滑出现(动画):10px 右:10px。

我不能使用任何库,只能使用 css 和 vanilla js。

我目前的解决方案如下:`

@keyframes example {
    from { top: -10px }
    to { top: 10px }
}

.navButton {
  position: fixed;
  top: 10px;
  right: 10px;
  z-index: 2000;
  animation-name: example;
  animation-duration: 3s;
  animation-iteration-count: 1;
}

`

该按钮最初在那里,然后当我刷新时,它从顶部出现,但严重滞后。

标签: javascriptcsscss-animations

解决方案


你的 CSS 对我来说很好。你使用的是什么浏览器?

为了让它更流畅,你可以像我在这里一样使用“从位置”和持续时间(在 Edge、Firefox 和 Chrome 中测试):

@keyframes example {
    from { top: -100px }
    to { top: 10px }
}

.navButton {
  position: fixed;
  top: 10px;
  right: 10px;
  z-index: 2000;
  animation-name: example;
  animation-duration: 1s;
  animation-iteration-count: 1;
}
<button class="navButton">test button</button>


推荐阅读