--- title: select slug: Web/API/Element/select_event tags: - Event translation_of: Web/API/Element/select_event ---
{{APIRef}}

select 选择某些文本时会触发事件。

该事件不适用于所有语言的所有元素。例如,在 HTML,select事件只能在表单{{HtmlElement('input/text', '<input type="text">')}}和 {{HtmlElement("textarea")}}元素上触发。

General info

Interface {{domxref("UIEvent")}} if generated from a user interface, {{domxref("Event")}} otherwise
Bubbles Yes
Cancelable No
Target {{domxref("Element")}}
Default Action None

属性

Property Type Description
target {{readonlyInline}} EventTarget The event target (the topmost target in the DOM tree).
type {{readonlyInline}} DOMString The type of event.
bubbles {{readonlyInline}} Boolean Whether the event normally bubbles or not.
cancelable {{readonlyInline}} Boolean Whether the event is cancellable or not.
view {{readonlyInline}} WindowProxy document.defaultView (window of the document)
detail {{readonlyInline}} long (float) 0.

示例

HTML

<input value="Try selecting some text in this element.">
<p id="log"></p>

JavaScript

function logSelection(event) {
  const log = document.getElementById('log');
  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
  log.textContent = `You selected: ${selection}`;
}

const input = document.querySelector('input');
input.addEventListener('select', logSelection);

结果

{{EmbedLiveSample("示例")}}

规范

Specification Status Comment
{{SpecName('UI Events', '#event-type-select', 'select')}} {{Spec2('UI Events')}}  

参见