最近使用electron实现一个简单的功能,下面这篇文章主要给大家介绍了关于Electron应用显示隐藏时展示动画效果的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
const win = new BrowserWindow({
width: 300,
height: 400,
frame: false, // 窗口边框
skipTaskbar: true, // 窗口是否不显示在任务栏上面
alwaysOnTop: true, // 窗口置顶
transparent: true, // 窗口透明
resizable: false,
webPreferences: {
// 通信文件 后面会用到
preload: path.join(__dirname, "preload.js"),
backgroundThrottling: false, // 后台运行是否禁止一些操作
建立系统托盘
import { Tray } from "electron";
// 传入图标路径
tray = new Tray(path.join(__dirname, "../../public/imgs/logo.ico"));
// 鼠标悬浮托盘时显示的文字
tray.setToolTip("Todo");
获取托盘坐标,实现应用在托盘上方
// 获取托盘所在位置信息
const { width, height, x, y } = tray.getBounds();
// 获取窗口信息 win 是 BrowserWindow 对象
const [w, h] = win.getSize();
// 刚好在正上方
win.setPosition(x + width / 2 - w / 2, y - h - 10);
// 封装成函数
const aboveTrayPosition = (win, tray) => {
const { width, height, x, y } = tray.getBounds();
const [w, h] = win.getSize();
return [x + width / 2 - w / 2, y - h - 10]
CSS 里面写上加载和退出的动画
动画应该添加到HTML根元素上,根元素必须得是 宽高 100%
@keyframes show {
opacity: 0;
transform: translateY(300px) scale(0);
100% {
opacity: 1;
transform: translateY(0) scale(1);
@keyframes hide {
opacity: 1;
transform: translateY(0) scale(1);
100% {
opacity: 0;
transform: translateY(300px) scale(0);
添加加载动画的事件
// preload.js
import { ipcRenderer } from "electron";
// 对应下面的 win.webContents.send("show");
// 默认有个 event 事件参数
ipcRenderer.on("show", (e) => {
const root = document.querySelector(".root") as HTMLElement;
root.style.animation = "show 0.3s linear forwards";
// 对应下面的 win.webContents.send("hide", s);
ipcRenderer.on("hide", (e, s: number) => {
const root = document.querySelector(".root") as HTMLElement;
root.style.animation = `hide ${s}s linear forwards`;
设置单击事件,单击显示或者隐藏程序并加载动画