回答編集履歴

2

誤字の修正

2020/01/18 06:59

投稿

yureighost
yureighost

スコア2183

test CHANGED
@@ -112,7 +112,7 @@
112
112
 
113
113
  if(e.button == 0){
114
114
 
115
- $('#first').off('keyup');
115
+ $('#first').off('keypress');
116
116
 
117
117
  }
118
118
 

1

追記

2020/01/18 06:59

投稿

yureighost
yureighost

スコア2183

test CHANGED
@@ -63,3 +63,59 @@
63
63
 
64
64
 
65
65
  javascriptのイベントの動作を再確認することをお勧めします。
66
+
67
+
68
+
69
+
70
+
71
+ **追記**
72
+
73
+ クリックしながらの要件なら離した時にkeypressイベントを削除しないと、
74
+
75
+ イベントが残り続けてキーボード押下でイベント発火し続けてしまいますね。
76
+
77
+ この場合はclickイベントを使うより、mousedownイベントでkeypressイベントを追加し、mouseupイベントで削除するのがいいかと思います。
78
+
79
+ 試しのサンプルコードを載せておきます。
80
+
81
+ ```javascript
82
+
83
+ $('#first').on('mousedown', (e)=>{
84
+
85
+ // マウスの左ボタンが押された場合
86
+
87
+ if(e.button == 0){
88
+
89
+ // 選択中のタグを切り替える
90
+
91
+ $('#second').removeClass('selected');
92
+
93
+ $('#first').addClass('selected');
94
+
95
+
96
+
97
+ $('#first').focus();
98
+
99
+ $('#first').on('keypress', (e)=>{
100
+
101
+ console.log("first",e.key)
102
+
103
+ });
104
+
105
+ }
106
+
107
+ });
108
+
109
+ $('#first').on('mouseup', (e)=>{
110
+
111
+ // マウスの左ボタンが離された場合
112
+
113
+ if(e.button == 0){
114
+
115
+ $('#first').off('keyup');
116
+
117
+ }
118
+
119
+ });
120
+
121
+ ```