CompositionEvent() - コンストラクタ
CompositionEvent()は、CompositionEventのコンストラクタです。新しいオブジェクトを作成します。
概要
- 名前
- CompositionEvent
- 所属
- CompositionEvent
- IDL
Constructor(DOMString type, optional CompositionEventInit eventInitDict) dictionary CompositionEventInit : UIEventInit { DOMString data = ""; }; dictionary UIEventInit : EventInit { Window? view = null; long detail = 0; }; dictionary EventInit { boolean bubbles = false; boolean cancelable = false; boolean composed = false; };
- 仕様書
- https://w3c.github.io/uievents/#dom-compositionevent-compositionevent
説明
第1引数(type)には、イベントの種類を表す文字列を指定します。
第2引数(eventInitDict)には、オブジェクトの各値をオブジェクトで定義します。指定できる固有のキーは下記の通りです。UIEvent()のキーを継承しています。
- data
- dataの値。初期値はnull。
チュートリアル
コンストラクタでCompositionEventを作成する例です。EventTarget.dispatchEvent()の引数にすれば、擬似的にイベントを発生させることができます。
var event = new CompositionEvent( "compositionupdate", {
data: "あ" ,
} ) ;
element.dispatchEvent( event ) ;
デモ
CompositionEvent()のデモです。ボタンをクリックすると、compositionupdateイベントのオブジェクトを作成して擬似的にイベントを発火させます。
<!-- このコードは編集できます。 -->
<!DOCTYPE html>
<html>
<head>
<style>
textarea#hoge {
width: 80% ;
min-height: 80px ;
font-size: 16px ;
}
div#result { white-space: pre-wrap ; }
</style>
</head>
<body>
<button id="create">イベントを作成</button>
<hr>
<textarea id="hoge"></textarea>
<hr>
<p>compositionupdateの発生回数→<span id="count">0</span></p>
<div id="result"></div>
<script>
var element = document.getElementById( "hoge" ) ;
element.addEventListener( "compositionupdate", getEventInfo ) ;
var number = 0 ;
document.getElementById( "create" ).onclick = function () {
var event = new CompositionEvent( "compositionupdate", {
data: "あ" ,
} ) ;
element.dispatchEvent( event ) ;
}
function getEventInfo( event ) {
document.getElementById( "result" ).textContent = "" ;
document.getElementById( "count" ).textContent = ++number ;
console.log( event ) ;
appendText( event + "\n" ) ;
appendText( "data: " + event.data + "\n" ) ;
}
function appendText ( text ) {
document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● 26+ | ● 53+ | ● 7.1+ | ● | × | ● 15+ | ● 7.0+ | ● 4.4+ |
関連記事
- KeyboardEvent()
- KeyboardEvent()は、KeyboardEventのコンストラクタです。新しいオブジェクトを作成します。
- InputEvent.isComposing
- isComposingは、InputEventのプロパティです。入力が未確定か否かを返します。例えば、日本語の全角で平仮名を入力して、まだ確定していない段階(漢字などに変換できる状態)ではtrueを返します。
- Document.getElementsByClassName()
- getElementsByClassName()は、Documentのメソッドです。class属性を指定して要素を取得します。
- CompositionEvent.data
- dataは、CompositionEventのプロパティです。入力操作により追加された、未確定状態の文字を返します。