使用Tauri创建APP的时候,默认的标题栏比较丑,但是如果去掉标题栏,窗口默认无法被拖动。本文将参考Tauri2.0官方文档解决这一问题。
一、修改tauri.conf.json文件
添加"decorations": false,即下面代码中的最后一行。
"app": {
"windows": [
{
"title": "star",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false,
"decorations": false
}
添加完以后,启动程序就会发现此时标题栏已经没有了,同时应用程序也无法拖动、无法关闭、无法放大缩小窗口了。
二、添加窗口权限
在src-tauri/capabilities/default.json文件中添加后面五个权限,分别为控制窗口拖拽、关闭、最小化、最大化、显示、隐藏窗口等权限的内容。
"permissions": [
"core:default",
"core:window:default",
"core:window:allow-start-dragging",
"core:window:allow-close",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-destroy",
"core:window:allow-hide",
"core:window:allow-show"
]
三、添加自定义标题栏和样式
在index.html文件中添加如下内容:
- 在body标签中添加如下内容:
<div data-tauri-drag-region class="titlebar">
<div class="titlebar-button" id="titlebar-minimize">
<img
src="https://api.iconify.design/mdi:window-minimize.svg"
alt="minimize"
/>
</div>
<div class="titlebar-button" id="titlebar-maximize">
<img
src="https://api.iconify.design/mdi:window-maximize.svg"
alt="maximize"
/>
</div>
<div class="titlebar-button" id="titlebar-close">
<img src="https://api.iconify.design/mdi:close.svg" alt="close"/>
</div>
</div>
注意,要将该div放在body最上层。另外data-tauri-drag-region
- 在
style标签中添加样式
<style>
.titlebar {
height: 30px;
background: #329ea3;
user-select: none;
display: flex;
justify-content: flex-end;
position: fixed;
top: 0;
left: 0;
right: 0;
}
.titlebar-button {
display: inline-flex;
justify-content: center;
align-items: center;
width: 30px;
height: 30px;
user-select: none;
-webkit-user-select: none;
}
.titlebar-button:hover {
background: #5bbec3;
}
</style>
3.在main.js中添加如下内容
import {Window} from '@tauri-apps/api/window';
const appWindow = new Window('main');
document
.getElementById('titlebar-minimize')
?.addEventListener('click', () => appWindow.minimize());
document
.getElementById('titlebar-maximize')
?.addEventListener('click', () => appWindow.toggleMaximize());
document
.getElementById('titlebar-close')
?.addEventListener('click', () => {
// 这一句的意思是关掉程序,appWindow.destroy()同样会关闭程序
// 对于有系统托盘(下一篇文章会讲)的程序而言点击关闭按钮并不是想退出程序,而是关闭窗口保留托盘,这时候需要使用appWindow.hide()隐藏主窗口,但是程序并没有被关闭。如果要显示主窗口可以在托盘事件中添加appWindow.show()代码,点击托盘可以再显示主窗口
appWindow.close()
});
添加完成以后,点击相关按钮如果没有效果可以查看控制台,看是否有报错,一般不生效是因为相关权限没有添加上。
四、最终效果
修改之前:
修改之后: