「jQuery」.focus、.blurでフォーカスイン、フォーカスアウトイベントを設定する
書式
$(“セレクタ名").focus(function(){処理コード
$(“セレクタ名").blur(function(){処理コード
focus、blurを使用してフォーカスイン/フォーカスアウトイベントを設定します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
//フォーカスインイベント
$("#username").focus(function(){
$(this).css("background-color", "red");
});
//フォーカスアウトイベント
$("#username").blur(function(){
$(this).css("background-color", "green");
});
});
</script>
</head>
<body>
<input type="text" id="username">
</body>
</html>
結果
テキストボックスにフォーカスを当てると背景色は「red」を変える。
テキストボックスにフォーカスを当てると背景色は「green」を変える。