Skip to content
扫码开始移动端阅读

需求

实现一个类似政府网站上的飘窗效果的公告栏

用途

可以非常强调的告诉用户。并且无脑的通知用户。每次刷新都会出现

实现

第一开始,想使用js控制窗口的滚动,比如类似我之前实现的一个弹窗。可以上下左右移动。只要加上参数。但是使用js。总感觉没有很优雅的感觉。太LOW了,

通过看了掘金大佬的文章《了解一下全新的CSS动画合成属性animation-composition》

然后直接上代码

vue
<script setup>
import { ref } from 'vue';
const isOpen = ref(true);
</script>
<template>
  <div
    v-if="isOpen"
    :class="(isDark && 'bg-black') || 'bg-white'"
    class="dialog rounded-lg shadow-lg animates hover:animate-pause">
    <h3 class="border-b border-black mb-4 text-xl leading-5 px-4">测试</h3>
    <p class="py-2 px-4 overflow-auto">这里是测试内容这里是测试内容这里是测试内容这里是测试</p>
    <div class="flex justify-end items-center p-4">
      <button class="btn btn-warning" @click="isOpen = false">关 闭</button>
    </div>
  </div>
</template>

<style scoped>
.dialog {
  top: 0;
  left: 0;
  width: 200px;
  z-index: 9999;
  position: fixed;
}
@keyframes horizontal {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(calc(100vw - 100%));
  }
}

@keyframes vertical {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(calc(100vh - 100%));
  }
}

.animates {
  animation:
    horizontal 18s infinite linear alternate,
    vertical 8s infinite linear alternate;
  animation-composition: accumulate;
  animation-delay: 0s, 0s;
  animation-fill-mode: both;
}

.hover\:animate-pause:hover {
  animation-play-state: paused;
}
</style>

实测效果

更多

  • 为什么使用css呢,因为不会阻塞线程,所以比js的动画效果更加的流畅。
  • 利用composition animation属性,可以实现多个动画的叠加。这样就可以实现多个方向的动画效果。
  • 查看这个css的支持情况:Can I use
  • 在mdn上查看更多的css动画属性:animation-composition