「JavaScript」addEventListenerの使い方

環境

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Windows 10 home 64bit
Google Chrome 103.0.5060.114
Windows 10 home 64bit Google Chrome 103.0.5060.114
Windows 10 home 64bit
Google Chrome 103.0.5060.114

構文
document.getElementById(要素).addEventListener (
“mouseup", function(){ 処理コード}
)
addEventListenerに「mouseup」を登録します。
addEventListener() は EventTarget インターフェイスのメソッドで、ターゲットに特定のイベントが配信されるたびに呼び出される関数を設定します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<div id="cft" >
<p>test</p>
</div>
<script>
document.getElementById("cft").addEventListener (
"mouseup", function(){ console.log('マウスから離れました12345')}
)
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <div id="cft" > <p>test</p> </div> <script> document.getElementById("cft").addEventListener ( "mouseup", function(){ console.log('マウスから離れました12345')} ) </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<div id="cft" >
  <p>test</p>
</div>
<script>

document.getElementById("cft").addEventListener ( 
  "mouseup", function(){ console.log('マウスから離れました12345')} 
)

</script>

</body>
</html>

実行結果
文字「test」をクリックしてマウスから離れた時に「マウスから離れました12345」が表示されます。

JavaScript

Posted by arkgame