我正在开始使用 Electron 构建桌面应用程序。我该如何自定义窗口标题栏(其中包含关闭、最小化和全屏按钮),以添加自定义视图? Safari 是我考虑的一个例子:
我要如何自定义 Electron 应用程序的窗口标题栏?例如:在标题栏中添加任意自定义视图,就像 Safari 一样。
.titlebar {
-webkit-user-select: none;
-webkit-app-region: drag;
}
第一个可以跨平台的选择是创建一个无边框窗口。第二个方法只适用于macOS,允许隐藏标题栏但保留窗口控件,从而允许添加自定义按钮。 例如:
const { BrowserWindow } = require('electron')
// This will create a window without titlebar, allowing for customization
let win = new BrowserWindow({ titleBarStyle: 'hidden' })
win.show()
然后您可以使用CSS属性-webkit-user-select
和-webkit-app-region
来指定拖动区域。
// main.js
window = new BrowserWindow({
titlebarStyle: 'hidden',
trafficLightPosition: {
x: 15,
y: 13, // macOS traffic lights seem to be 14px in diameter. If you want them vertically centered, set this to `titlebar_height / 2 - 7`.
},
})
然后使用 HTML + CSS 创建自己的临时标题栏:
<!-- index.html -->
<body>
<header class="titlebar"></header>
...
</body>
/* styles.css */
.titlebar {
background-color: #f0f0f0;
height: 40px;
border-bottom: 1px solid #d0d0d0;
-webkit-app-region: drag; /* Allow user to drag the window using this titlebar */
-webkit-user-select: none; /* Prevent user from selecting things */
user-select: none;
}
请注意标题栏出现在滚动条下方。甚至当用户滚动时,它也会移动。我们需要通过将标题栏以下的所有内容包装在<div class="main-content">
中,并添加这些样式来将其与可滚动内容分开:
.main-content {
height: calc(100vh - 40px); /* Force the content to take up the viewport height minus the titlebar height */
overflow: auto; /* Allow the main content to be scrollable */
}
body {
overflow: hidden; /* Make the HTML body be non-scrollable */
}
现在,您可以添加任何想要的HTML内容到那里。