jQuery focusでフォーカスされたら発動サンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

構文
1.テキストボックスがフォーカスされたら発動します。
$('input[type="text"]’).forcus(function(){処理コード1
})
2.テキストボックスのフォーカスが外れたら発動します。
$(セレクタ).blur(function(){処理コード2});

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//テキストボックスがフォーカスされたら発動する
$('input[type="text"]').focus(function(){
//背景色を変える
$(this).css('background', 'skyblue');
//テキストボックスのフォーカスが外れたら発動する
}).blur(function() {
//背景色を戻す
$(this).css('background', '#fff');
});
});
</script>
</head>
<body>
<input type="text" name="username" value="山田">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ //テキストボックスがフォーカスされたら発動する $('input[type="text"]').focus(function(){ //背景色を変える $(this).css('background', 'skyblue'); //テキストボックスのフォーカスが外れたら発動する }).blur(function() { //背景色を戻す $(this).css('background', '#fff'); }); }); </script> </head> <body> <input type="text" name="username" value="山田"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

 //テキストボックスがフォーカスされたら発動する
  $('input[type="text"]').focus(function(){
    //背景色を変える
    $(this).css('background', 'skyblue');
    //テキストボックスのフォーカスが外れたら発動する
  }).blur(function() {
    //背景色を戻す
    $(this).css('background', '#fff');
 
  });
});
</script>
</head>
<body>

<input type="text" name="username" value="山田">

</body>
</html>

実行結果
テキストボックスをクリックしてフォーカスすると背景色(skyblue)が変わり、フォーカスを外すと背景色(#fff)が戻ります。

jQuery

Posted by arkgame