MathMLElement:focus() 方法

Baseline 已廣泛支援

此功能已成熟,並且在眾多裝置和瀏覽器版本上都能正常工作。自 2023 年 1 月以來,它已在各瀏覽器中可用。

MathMLElement 介面的 focus() 方法將焦點設定到指定的 MathML 元素上(如果該元素可以獲取焦點)。獲取焦點的元素是預設接收鍵盤和類似事件的元素。

預設情況下,瀏覽器會在元素獲取焦點後將其滾動到檢視中,並且可能會提供獲取焦點的元素的可見指示(通常是透過在元素周圍顯示“焦點環”)。提供了引數選項來停用預設滾動並強制在元素上顯示可見指示。如果你在 mousedown 事件處理程式中呼叫 focus(),則必須呼叫 event.preventDefault() 以防止焦點離開 MathMLElement

語法

js
focus()
focus(options)

引數

options 可選

用於控制焦點設定過程各個方面的物件。此物件可能包含以下屬性

preventScroll 可選

一個布林值,指示瀏覽器是否應滾動文件以將新獲得的焦點元素帶入視口。preventScroll 的值為 false(預設值)表示瀏覽器在聚焦元素後會將其滾動到視口。如果將 preventScroll 設定為 true,則不會發生滾動。

返回值

無(undefined)。

示例

使 MathML 元素獲取焦點

此示例使用一個按鈕將焦點設定到 MathML 圓形元素上。

HTML

html
<div>
  <math>
    <msup id="myMath" tabindex="0">
      <mi>x</mi>
      <mn>2</mn>
    </msup>
  </math>
  <button id="focusButton">Focus the Math</button>
</div>

JavaScript

js
const mathElement = document.getElementById("myMath");

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

結果

規範

規範
HTML
# dom-focus-dev

瀏覽器相容性

另見