ゆっくりしたい日曜日

10:00

おはようございます。一つ大きな仕事(退院)が片づいたので、今日はゆっくりしたいと思います。

知的生産の技術書019~022「超」整理法シリーズ | シゴタノ!

Textbox:

ボタンのフォーカス処理がうまくいっていないので、それを改善します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 document.addEventListener("keydown", event => {
    if (event.metaKey && event.keyCode === 39) {
      var current = document.activeElement;
      if (current.getAttribute("type") == "linkbtn"){
        var next = current.nextElementSibling;
        if (next) {
          next.focus();
        }else{
          var parent = current.parentNode;
          parent.firstElementChild.focus();
       }
      }else{
        document.querySelector('button[type="linkbtn"]').focus();
      }   
    }
  });

なんか、むっちゃダサイですが、とりあえずOKです。フォーカスがボタンにない場合にショートカットキーを押すと、一番最初のボタンにフォーカスを合わせるようにしました。

ちょっとifが多すぎて、コードの中身が後から追いにくくなっているのが気になりますが、他の書き方が思いつかないので、とりあえずこれでよしとしましょう。

* * *

ん?

キーを押したあとに、今のフォーカスを確認する関数に処理を投げればよい?

* * *

すっきりしませんな。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  document.addEventListener("keydown", event => {
    if (event.metaKey && event.keyCode === 37) {
      const current = checkCurrentBtn(document.activeElement);
      if (current){
        previous = current.previousElementSibling;
      }else{
        return false
      }
      if (previous){
        previous.focus();
      }else{
        const parent = current.parentNode;
        parent.lastElementChild.focus();
      }
    }
  });

function checkCurrentBtn(current){
  if (! (current.getAttribute("type") == "linkbtn") ){
    document.querySelector('button[type="linkbtn"]').focus();
    return false;
  }else{
    return current;
  }
}

ただ、階層が深くなるのは避けられました。関数に変数を二つ与えて、前の項目 or 後ろの項目を帰す、とするとすっきり書けますが、あまりにも特化型関数な気がするのでちょっと断念。

とりあえずはよしとしましょう。