jQuery キーボードによって要素を操作する方法 – キーの取得とその活用に関して

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんばんは。今回のネタは【キーボードによって要素を操作する方法 – キーの取得とその活用に関して】です。矢印キーを使用したページ遷移等、その活躍の場は結構広いです。工夫次第では色々と面白い活用方法や便利な活用方法がありそうですね。

キーの取得と要素の操作

jQuery


$(window).keyup(function(e){
alert(e.keyCode);
});

この3行でキーに割り振られたコードを取得できます。例えば…ESCキーは【27】です。ESCキーを押したら特定の要素を削除、というような場合は以下のように記述できます。

$(window).keyup(function(e){
if(e.keyCode == 27){$(‘#id名’).remove()}
});

キーコードの取得

キーコードを取得し表示しています。知りたいキーがありましたら押してみてください。


キーコード一覧はコチラ

キーコード取得 – DEMO

本デモでは矢印キーを取得し、特定要素にアニメーションを加えています。遊び要素等、どこかでうまく使えたら面白いかもしれませんね。

HTML

<p id="ball"></p>
<p id="holl"></p>
jQuery

$(function(){

ramR = 0;
ramG = 0;
ramB = 0;

setInterval(
function(){
$(‘#container span:first’).animate({‘opacity’:’0′},500,function(){
$(‘#container span:first’).remove();
});
},500);

function getball(){
var bx = $("#ball").css(‘left’);
var by = $("#ball").css(‘top’);
if( bx == ‘500px’ && by == ‘500px’){
ramR = parseInt(Math.random()*255);
ramG = parseInt(Math.random()*255);
ramB = parseInt(Math.random()*255);
$("#ball").css({‘background-color’:’rgb(‘+ ramR +’,’+ ramG +’,’+ ramB +’)’});
$("#holl").css({‘background-color’:’rgb(‘+ ramR +’,’+ ramG +’,’+ ramB +’)’});
}
};

function getball_past(){
var bx2 = $("#ball").css(‘left’);
var by2 = $("#ball").css(‘top’);
//$(‘#debug3’).html(bx2);
//$(‘#debug4’).html(by2);
$(‘#container’).append(‘<span style="left:’ + bx2 +’; top:’+ by2 +’;" class="ball_past"></span>’);
$(".ball_past:last-child").css({‘background-color’:’rgb(‘+ ramR +’,’+ ramG +’,’+ ramB +’)’});
}

$(window).keyup(function(e){
if(e.keyCode == 37){$(‘#ball’).not(‘:animated’).animate({‘left’: ‘-=100px’},100,function(){getball();});}
if(e.keyCode == 38){$(‘#ball’).not(‘:animated’).animate({‘top’: ‘-=100px’},100,function(){getball();});}
if(e.keyCode == 39){$(‘#ball’).not(‘:animated’).animate({‘left’: ‘+=100px’},100,function(){getball();});}
if(e.keyCode == 40){$(‘#ball’).not(‘:animated’).animate({‘top’: ‘+=100px’},100,function(){getball();});}
getball_past();
});

});

CSS

#ball{
height: 50px;
width: 50px;
position: absolute;
background: #000;
border-radius:25px;
top:0px;
left:0px;
z-index: 999;
}
.ball_past{
height: 50px;
width: 50px;
position: absolute;
background: #000;
border-radius:25px;
opacity: 0.3;
}

#holl{
height: 80px;
width: 80px;
position: absolute;
background: #000;
border-radius:40px;
top:485px;
left:485px;
z-index: 1000;
}

以上になります。