2009年6月8日月曜日

jQuery::Up/Downキーでフォームを移動、パート5:完成コードとデモ

 (1)動作デモ
 ブログ上で動かなかったので、ここでフォームのUp/Downデモ版を公開してます。 IE6、IE7、Chromeで動いてます。 FireFoxは基本的には動いてますが、とセレクトで挙動がおかしいです。

【追記2009/06/11:Safariでも動きました。ちなみにWindows Vistaです】
【追記2011/12/26:githubでソースコード公開してます。
 コードはかなり変わっていますので、githubのほうを参照してください。】

  (2)全部入りソースコード
<script language="javascript" type="text/javascript" src="./jquery-1.3.2.min.js"></script>
<script language="javascript" type="text/javascript" src="./jquery.hotkeys-0.7.8.js"></script>
<SCRIPT LANGUAGE="JavaScript">
<!--
var focusElem;  // フォーカスされたオブジェクトそのもの
var jFormElem;  // フォーム内のエレメント一覧(jQueryオブジェクト)
var jFormLeng;  // エレメントの数

$(document).ready( function()
{
// フォーム要素の配列を生成。
jFormElem =
   $( 'form' ).map( function() {
       var ele = $.makeArray( this.elements );
       return ele;
   }).filter( function() {
       if( this.type == 'hidden' ) {
           return false;
       }
       return true;
   }).each( function(i) {
       $(this).attr( 'focusIndex', i );
   });
jFormLeng = jFormElem.length;

// フォームエレメントがフォーカスされたら記録。
$(jFormElem).focus( function() {
   focusElem = jQuery( this );
});
// 要素#0にフォーカスを当てる。
jFormElem.get(0).focus();

// DOWNキーが押された場合の処理。
$(jFormElem).bind( 'keydown', 'down', function( event )
{
   var keyPropagate = true;
   if( !focusElem ) return keyPropagate;
   if( !$(focusElem).attr( 'focusIndex' ) ) return keyPropagate;
   if(  $(focusElem).attr( 'type' ) == 'textarea' ) return keyPropagate;

   var fIndex = parseInt( $(focusElem).attr( 'focusIndex' ) );

   if( fIndex == jFormLeng-1 ) {
       $(jFormElem).get(0).focus();
   }
   else {
       $(jFormElem).get( fIndex+1 ).focus();
   }
   keyPropagate = false;
   return keyPropagate;
});
// UPキーが押された場合の処理。
$(jFormElem).bind( 'keydown', 'up', function( event )
{
   var keyPropagate = true;
   if( !focusElem ) return keyPropagate;
   if( !$(focusElem).attr( 'focusIndex' ) ) return keyPropagate;
   if(  $(focusElem).attr( 'type' ) == 'textarea' ) return keyPropagate;

   var fIndex = parseInt( $(focusElem).attr( 'focusIndex' ) );
   if( fIndex == 0 ) {
       $(jFormElem).get( jFormLeng-1 ).focus();
   }
   else {
       $(jFormElem).get( fIndex-1 ).focus();
   }
   keyPropagate = false;
   return keyPropagate;
});
});
-->
</script>

0 件のコメント: