▼検索ボックスに何も入力されていない時はヒントテキスト画像を表示し、そうでない時はヒント画像を表示しません。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="ja" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta http-equiv="imagetoolbar" content="no" /> <title>イベント操作:イベントヘルパー:focusイベントの使用例 | jQuery</title> <link rel="stylesheet" type="text/css" href="/content/lib/global.css" /> <!-- JS --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ if($("input#query").val()!=""){ $(this).addClass("nohint"); }else{ $($("input#query")).addClass("hint"); } $("input#query").focus(function(){ /* フォーカスが当たった時、何も入力されていなかったら背景画像を消す */ if($(this).val()=="") $(this).removeClass("hint").addClass("nohint"); }).blur(function(){ /* フォーカスが外れた時、何も入力されていなかったら背景画像を表示 */ if($(this).val()=="") $(this).removeClass("nohint").addClass("hint"); }); }); </script> <!-- CSS --> <style type="text/css"> #query { width:150px; height:20px; background:#fff; border:1px solid #ccc; vertical-align:middle; } #query.hint { background:#fff url("/content/img/ajax/bg_search.png") no-repeat left center; } #query.nohint { background:#fff; } </style> <link rel="stylesheet" type="text/css" href="/common/css/example.css"></head> <body id='example3' class='example'><div class="ads" style="margin:32px auto;text-align:center;"></div><h1 class='h'><a href='/'>PHP & JavaScript Room</a> :: 設置サンプル</h1> <h3 class='h'>実行結果</h3> <div id="wrap"> <h1>イベント操作:イベントヘルパー:focusイベントの使用例 | jQuery</h1> <p>▼検索ボックスに何も入力されていない時はヒントテキスト画像を表示し、そうでない時はヒント画像を表示しません。 </p> <!-- CODE --> <form action="#"> <input type="text" name="query" id="query" title="サイト内検索" /> <input type="submit" value="検索" onclick="return false;" /> </form> <!-- CODE / --> </div> </body> </html>