---
title: "快捷键"
description: "快捷键"
language: "zh"
canonical: "https://x6.antv.antgroup.com/zh/tutorial/plugins/keyboard/"
version: "3.x"
---

[资料索引](/llms.txt)

> **在本章节中主要介绍快捷键插件相关的知识，通过阅读，你可以了解到**

- 如何为画布绑定快捷键


## 使用

你可以通过插件 `Keyboard` 启用快捷键功能，示例：

```ts
import { Graph, Keyboard } from '@antv/x6'

const graph = new Graph({
  background: {
    color: '#F2F7FA',
  },
})
graph.use(
  new Keyboard({
    enabled: true,
  }),
)
```

## 演示



```ts
import './index.less'
import { createRoot } from 'react-dom/client'
import * as React from 'react'
import { Graph, Clipboard, Keyboard, Selection } from '@antv/x6'

export default class Example extends React.Component {
  private container: HTMLDivElement
  private graph: Graph

  componentDidMount() {
    this.graph = new Graph({
      container: this.container,
      background: {
        color: '#F2F7FA',
      },
    })

    this.graph.use(
      new Clipboard({
        enabled: true,
      }),
    )
    this.graph.use(
      new Selection({
        enabled: true,
        showNodeSelectionBox: true,
      }),
    )
    this.graph.use(
      new Keyboard({
        enabled: true,
        global: true,
      }),
    )

    this.graph.addNode({
      x: 280,
      y: 100,
      width: 100,
      height: 40,
      label: 'Rect',
      attrs: {
        body: {
          stroke: '#8f8f8f',
          strokeWidth: 1,
          fill: '#fff',
          rx: 6,
          ry: 6,
        },
      },
    })

    const source = this.graph.addNode({
      x: 32,
      y: 32,
      width: 100,
      height: 40,
      label: 'Hello',
      attrs: {
        body: {
          stroke: '#8f8f8f',
          strokeWidth: 1,
          fill: '#fff',
          rx: 6,
          ry: 6,
        },
      },
    })

    const target = this.graph.addNode({
      shape: 'circle',
      x: 160,
      y: 180,
      width: 60,
      height: 60,
      label: 'World',
      attrs: {
        body: {
          stroke: '#8f8f8f',
          strokeWidth: 1,
          fill: '#fff',
        },
      },
    })

    this.graph.addEdge({
      source,
      target,
      attrs: {
        line: {
          stroke: '#8f8f8f',
          strokeWidth: 1,
        },
      },
    })

    this.graph.bindKey('ctrl+c', () => {
      const cells = this.graph.getSelectedCells()
      if (cells.length) {
        this.graph.copy(cells)
      }
      return false
    })

    this.graph.bindKey('ctrl+v', () => {
      if (!this.graph.isClipboardEmpty()) {
        const cells = this.graph.paste({ offset: 32 })
        this.graph.cleanSelection()
        this.graph.select(cells)
      }
      return false
    })
  }

  refContainer = (container: HTMLDivElement) => {
    this.container = container
  }

  render() {
    return (
      <div className="keyboard-app">
        <div className="app-info">
          <p>
            <span>Ctrl + C</span>Copy Cell
            <span style={{ marginLeft: 24 }}>Ctrl + V</span>Paste Cell
          </p>
        </div>
        <div className="app-content" ref={this.refContainer} />
      </div>
    )
  }
}

const root = createRoot(document.getElementById('container')!)
root.render(<Example />)
window.addEventListener('pagehide', () => root.unmount(), { once: true })
```



## 配置

| 属性名 | 类型                                      | 默认值  | 必选 | 描述                                                                                                                                       |
|--------|-------------------------------------------|---------|------|------------------------------------------------------------------------------------------------------------------------------------------|
| global | boolean                                   | `false` |      | 是否为全局键盘事件，设置为 `true` 时键盘事件绑定在 `document` 上，否则绑定在画布容器上。当绑定在画布容器上时，需要容器获得焦点才能触发键盘事件 |
| format | `(this: Graph, key: string) => string`    | -       |      | 绑定或解绑键盘事件时，格式化按键字符串                                                                                                      |
| guard  | `(this: Graph, e: KeyboardEvent) => boolean` | -    |      | 判断一个键盘事件是否应该被处理，返回 `false` 时对应的键盘事件被忽略                                                                         |

`format` 和 `guard` 配置使用如下：

```ts
graph.use(
  new Keyboard({
    enabled: true,
    format(key) {
      return key.replace(/\s/g, '').replace('cmd', 'command')
    },
  }),
)
// 下面语句被格式化后等同于 graph.bindKey('command', (e) => { })
graph.bindKey('cmd', (e) => {})

graph.use(
  new Keyboard({
    enabled: true,
    guard(this: Graph, e: KeyboardEvent) {
      if (e.altKey) {
        // 当按下 alt 键时，忽略所有键盘事件
        return false
      }
      return true
    },
  }),
)
```

## API

### graph.bindKey(...)

```ts
bindKey(
  keys: string | string[],
  callback: (e: KeyboardEvent) => void,
  action?: 'keypress' | 'keydown' | 'keyup',
): this
```

绑定快捷键。

### graph.unbindKey(...)

```ts
unbindKey(
  keys: string | string[],
  action?: 'keypress' | 'keydown' | 'keyup',
): this
```

解绑快捷键。

### graph.clearKeys()

```ts
clearKeys(): this
```

清除所有快捷键。

### graph.triggerKey()

```ts
triggerKey(
  keys: string,
  action?: 'keypress' | 'keydown' | 'keyup',
): this
```

手动触发快捷键。

### graph.isKeyboardEnabled()

```ts
isKeyboardEnabled(): boolean
```

获取是否启用了键盘事件。

### graph.enableKeyboard()

```ts
enableKeyboard(): this
```

启用键盘事件。

### graph.disableKeyboard()

```ts
disableKeyboard(): this
```

禁用键盘事件。

### graph.toggleKeyboard(...)

```ts
toggleKeyboard(enabled?: boolean): this
```

切换键盘事件的启用状态。参数如下：

| 名称    | 类型    | 必选 | 默认值 | 描述                                           |
|---------|---------|:----:|--------|----------------------------------------------|
| enabled | boolean |      | -      | 是否启用键盘事件，缺省时切换键盘事件的启用状态。 |
### docs/demos/tutorial/plugins/keyboard/index.less

```less
.keyboard-app {
  border: 1px solid #f0f0f0;
  padding: 16px 8px;
  font-family: sans-serif;

  .app-info {
    bottom: 0;
    margin: 0;
    padding: 0 8px;
  }

  .app-info span {
    display: inline-block;
    margin-right: 8px;
    padding: 2px 8px;
    font-size: 12px;
    line-height: 18px;
    background: #e9e9e9;
    border-radius: 4px;
  }

  .app-content {
    width: 100%;
    height: 280px;
    margin-right: 8px;
    margin-left: 8px;
    box-shadow: 0 0 10px 1px #e9e9e9;
  }

  .x6-widget-selection-box {
    border: 2px dashed #239edd;
  }

  .x6-widget-selection-inner {
    border: 1px solid #239edd;
  }
}
```
