如何自定义 Electron 应用程序的窗口标题栏?

28

我正在开始使用 Electron 构建桌面应用程序。我该如何自定义窗口标题栏(其中包含关闭、最小化和全屏按钮),以添加自定义视图? Safari 是我考虑的一个例子:

safar title bar


我要如何自定义 Electron 应用程序的窗口标题栏?例如:在标题栏中添加任意自定义视图,就像 Safari 一样。

4
你可以访问http://photonkit.com/。 - Alessandro Loziobiz Bisi
1
@AlessandroLoziobizBisi 哇!那正是我需要的。谢谢! - Andrew
3个回答

30
您在Electron中的唯一选择是创建一个frameless(也称为无边框)窗口,然后使用CSS创建“虚假”标题栏,包括所需的任何UI元素。
Electron/webkit提供了CSS属性,允许您使任何元素可拖动,就像标题栏一样:
.titlebar {
  -webkit-user-select: none;
  -webkit-app-region: drag;
}

21

第一个可以跨平台的选择是创建一个无边框窗口。第二个方法只适用于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来指定拖动区域。


5
通过创建无边框窗口来隐藏默认标题栏:
// 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内容到那里。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接