Skip to content
Tauri 中文网

窗口自定义

Tauri 提供了许多选项来自定义应用窗口的外观。你可以创建自定义标题栏、使用透明窗口、强制执行大小限制等。

¥Tauri provides lots of options for customizing the look and feel of your app’s window. You can create custom titlebars, have transparent windows, enforce size constraints, and more.

配置

¥Configuration

有三种方法可以更改窗口配置:

¥There are three ways to change the window configuration:

使用

¥Usage

创建自定义标题栏

¥Creating a Custom Titlebar

这些窗口功能的一个常见用途是创建自定义标题栏。本简短教程将指导你完成该过程。

¥A common use of these window features is creating a custom titlebar. This short tutorial will guide you through that process.

:::note 注意

对于 macOS,使用自定义标题栏也会丢失系统提供的一些功能,例如 移动或对齐窗口。自定义标题栏但保留原生功能的另一种方法是使标题栏透明并设置窗口背景颜色。参见 (macOS)带有自定义窗口背景颜色的透明标题栏 的使用方法。

¥For macOS, using a custom titlebar will also lose some features provided by the system, such as moving or aligning the window. Another approach to customizing the titlebar but keeping native functions could be making the titlebar transparent and setting the window background color. See the usage (macOS) Transparent Titlebar with Custom Window Background Color.

:::

tauri.conf.json

在你的 tauri.conf.json 中将 decorations 设置为 false

¥Set decorations to false in your tauri.conf.json:

tauri.conf.json
"tauri": {
"windows": [
{
"decorations": false
}
]
}

权限

¥Permissions

在功能文件中添加窗口权限。

¥Add window permissions in capability file.

默认情况下,所有插件命令都被阻止并且无法访问。你必须在 capabilities 配置中定义权限列表。

¥By default, all plugin commands are blocked and cannot be accessed. You must define a list of permissions in your capabilities configuration.

有关更详细的说明,请参阅 功能概述

¥See the Capabilities Overview for more information and the step by step guide to use plugin permissions.

src-tauri/capabilities/default.json
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main-capability",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": ["core:window:default", "core:window:allow-start-dragging"]
}
权限描述
core:window:default插件的默认权限。除 window:allow-start-dragging 外。
core:window:allow-close启用 close 命令,没有任何预配置范围。
core:window:allow-minimize启用 minimal 命令,没有任何预配置范围。
core:window:allow-start-dragging启用 start_dragging 命令,无需任何预配置范围。
core:window:allow-toggle-maximize启用 toggle_maximize 命令,无需任何预配置范围。
core:window:allow-internal-toggle-maximize启用 internal_toggle_maximize 命令,没有任何预配置范围。

CSS

添加此 CSS 示例以将其保持在屏幕顶部并设置按钮样式:

¥Add this CSS sample to keep it at the top of the screen and style the buttons:

.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;
}

HTML

将其放在 <body> 标签的顶部:

¥Put this at the top of your <body> tag:

<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>

请注意,你可能需要将其余内容向下移动,以便标题栏不会覆盖它。

¥Note that you may need to move the rest of your content down so that the titlebar doesn’t cover it.

JavaScript

使用此代码片段使按钮工作:

¥Use this code snippet to make the buttons work:

import { getCurrentWindow } from '@tauri-apps/api/window';
// when using `"withGlobalTauri": true`, you may use
// const { getCurrentWindow } = window.__TAURI__.window;
const appWindow = getCurrentWindow();
document
.getElementById('titlebar-minimize')
?.addEventListener('click', () => appWindow.minimize());
document
.getElementById('titlebar-maximize')
?.addEventListener('click', () => appWindow.toggleMaximize());
document
.getElementById('titlebar-close')
?.addEventListener('click', () => appWindow.close());

请注意,如果你使用基于 Rust 的前端,则可以将上述代码复制到 index.html 文件中的 <script> 元素中。

¥Note that if you are using a Rust-based frontend, you can copy the code above into a <script> element in your index.html file.

:::note 注意

data-tauri-drag-region 仅适用于直接应用它的元素。如果你希望拖动行为也应用于子元素,则需要将其单独添加到每个子元素。

¥data-tauri-drag-region will only work on the element to which it is directly applied. If you want the drag behavior to apply to child elements as well, you’ll need to add it to each child individually.

保留此行为,以便按钮和输入等交互元素可以正常运行。

¥This behavior is preserved so that interactive elements like buttons and inputs can function properly.

:::

手动实现 data-tauri-drag-region

¥Manual Implementation of data-tauri-drag-region

对于自定义拖动行为的用例,你可以手动使用 window.startDragging 添加事件监听器,而不是使用 data-tauri-drag-region

¥For use cases where you customize the drag behavior, you can manually add an event listener with window.startDragging instead of using data-tauri-drag-region.

HTML

从上一节的代码中,我们删除了 data-tauri-drag-region 并添加了 id

¥From the code in the previous section, we remove data-tauri-drag-region and add an id:

<div data-tauri-drag-region class="titlebar">
<div id="titlebar" class="titlebar">
<!-- ... -->
</div>
</div>

Javascript

向标题栏元素添加事件监听器:

¥Add an event listener to the titlebar element:

// ...
document.getElementById('titlebar')?.addEventListener('mousedown', (e) => {
if (e.buttons === 1) {
// Primary (left) button
e.detail === 2
? appWindow.toggleMaximize() // Maximize on double click
: appWindow.startDragging(); // Else start dragging
}
});

(macOS)带有自定义窗口背景颜色的透明标题栏

¥(macOS) Transparent Titlebar with Custom Window Background Color

我们将创建主窗口并从 Rust 端更改其背景颜色。

¥We are going to create the main window and change its background color from the Rust side.

tauri.conf.json 文件中删除主窗口:

¥Remove the main window from the tauri.conf.json file:

tauri.conf.json
"tauri": {
"windows": [
{
"title": "Transparent Titlebar Window",
"width": 800,
"height": 600
}
],
}

cocoa 包添加到依赖,以便我们可以使用它来调用 macOS 原生 API:

¥Add cocoa crate to dependencies so that we can use it to call the macOS native API:

src-tauri/Cargo.toml
[target."cfg(target_os = \"macos\")".dependencies]
cocoa = "0.26"

创建主窗口并更改其背景颜色:

¥Create the main window and change its background color:

src-tauri/src/lib.rs
use tauri::{TitleBarStyle, WebviewUrl, WebviewWindowBuilder};
pub fn run() {
tauri::Builder::default()
.setup(|app| {
let win_builder =
WebviewWindowBuilder::new(app, "main", WebviewUrl::default())
.title("Transparent Titlebar Window")
.inner_size(800.0, 600.0);
// set transparent title bar only when building for macOS
#[cfg(target_os = "macos")]
let win_builder = win_builder.title_bar_style(TitleBarStyle::Transparent);
let window = win_builder.build().unwrap();
// set background color only when building for macOS
#[cfg(target_os = "macos")]
{
use cocoa::appkit::{NSColor, NSWindow};
use cocoa::base::{id, nil};
let ns_window = window.ns_window().unwrap() as id;
unsafe {
let bg_color = NSColor::colorWithRed_green_blue_alpha_(
nil,
50.0 / 255.0,
158.0 / 255.0,
163.5 / 255.0,
1.0,
);
ns_window.setBackgroundColor_(bg_color);
}
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

Tauri 中文网 - 粤ICP备13048890号