自定义标题栏
基础教程
应用窗口有OS设置的默认窗口外框(chrome)。 不要与Google Chrome浏览器混淆, 窗口外框(chrome) 是指窗口中不是主网页内容的部分(如标题栏,工具栏,控件)。 虽然OS的窗口外框提供的默认标题栏对于简单用例足够了,但是很多应用选择去除它。 实现一个自定义的标题栏可以使您的应用更有现代感,并在多个平台中保持一致。
你可以打开有以下初始代码的Fiddle来跟随本教程。
让我们先配置一个有原生窗口控件和隐藏标题栏的窗口。
要移除默认标题栏,将 BrowserWindow 构造函数中的BaseWindowContructorOptions titleBarStyle
参数设置为'hidden'。
在MacOS上,设置titleBarStyle: 'hidden'会去除标题栏,保留窗口左上角的红绿灯控件。 但是在Windows和Linux上,你需要通过设置 BrowserWindow 构造函数的BaseWindowContructorOptions titleBarOverlay参数来将窗口控件添加回你的BrowserWindow。
创建自定义标题栏
现在,让我们在 BrowserWindow 的 webContents 中实现一个简单的自定义标题栏。
这并不花哨,只是HTML和CSS!
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<metahttp-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<linkhref="./styles.css"rel="stylesheet">
<title>Custom Titlebar App</title>
</head>
<body>
<!-- mount your title bar at the top of you application's body tag -->
<divclass="titlebar">Cool titlebar</div>
</body>
</html>
body{
margin:0;
}
.titlebar{
height:30px;
background:blue;
color:white;
display: flex;
justify-content: center;
align-items: center;
}
目前我们的应用窗口不能被移动。 我们已经删除了默认标题栏,应用需要告诉Electron 哪些区域可以拖拽。 我们通过添加
样式的 app-region: drag 到自定义标题栏来做到这一点。 现在我们可以拖动自定义标题栏来重新定位我们的应用窗口了!
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<metahttp-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<linkhref="./styles.css"rel="stylesheet">
<title>Custom Titlebar App</title>
</head>
<body>
<!-- mount your title bar at the top of you application's body tag -->
<divclass="titlebar">Cool titlebar</div>
</body>
</html>
body{
margin:0;
}
.titlebar{
height:30px;
background:blue;
color:white;
display: flex;
justify-content: center;
align-items: center;
app-region: drag;
}