大网数据广告活动
Web 标准与前端开发

SVGElement: focus() method

· 52CE 我爱测

The **`SVGElement.focus()`** method sets focus on the specified SVG element, if it can be focused. The focused element is the element that will receive keyboard and similar events by default.

SVG

The SVGElement.focus() method sets focus on the specified SVG element, if it can be focused. The focused element is the element that will receive keyboard and similar events by default.

By default the browser will scroll the element into view after focusing it, and it may also provide visible indication of the focused element (typically by displaying a "focus ring" around the element). Parameter options are provided to disable the default scrolling and force visible indication on elements.

Syntax

focus()
focus(options)

Parameters

  • options
    • : An optional object for controlling aspects of the focusing process. This object may contain the following properties:
      • preventScroll
        • : A boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur.

Return value

None (undefined).

Examples

Focusing an SVG element

This example uses a button to set the focus on an SVG circle element.

HTML

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
  <circle id="myCircle" cx="100" cy="100" r="50" tabindex="0" fill="blue" />
  <button id="focusButton">Focus the circle</button>
</svg>

JavaScript

document.getElementById("focusButton").addEventListener("click", () => {
  const circle = document.getElementById("myCircle");
  circle.focus();
});

Specifications

Notes

  • If you call SVGElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the SVGElement

Browser compatibility

See also

  • SVGElement.blur to remove the focus from an element.
  • HTMLElement.focus a similar method for HTML elements.

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。