0

I have 3 div parts in my HTML document, and i am trying to toggle between each other whenever the key press. The idea is, when a key press event is occured, i got the id of the current div and depending on that id, i fade in the right div(if it's div 1, fade in div 2, etc.).

My HTML code is the following:

<div id="home" class="current">
        <p align="center">Home</p>
        <p align="center">
           Some content
        </p>
    </div>
    <div id="about">
        <p align="center">About</p>
        <p align="center">
           Some content 
        </p>
    </div>
    <div id="contact">
        <p align="center">Contact Form</p>
        <p align="center">
            Some content
        </p>
    </div>

The jQuery code:

<script>
$("#target").keypress(function(){

        var id = $(this).html().toLowerCase();
          console.log('id is: '+id);    
        $('.current').fadeOut(900, function(){
            $('#'+id).fadeIn(900);
            $('.current').removeClass('current');
            $('#'+id).addClass('current');

        });

    });
</script>
​

The code above doesn't work, i am new with jQuery events, could you please guiding me to the right way.

4

2 に答える 2

1

代わりにkeyupとを使用してください。.val

$("#target").keyup(function(){

    var id = $(this).val().toLowerCase();
    $('.current').removeClass('current').fadeOut(900, function(){
        $('#'+id).fadeIn(900).addClass('current');
    });

});
于 2012-09-18T00:35:53.040 に答える
1

イベントリスナーが必要です。keyCode条件ステートメントを(特定のキーではなく)任意のキーにしたい場合は、削除できます。

$(document).keyup(function(e) {
 if (e.keyCode == 13) {             // enter key
  var id = $('.current').attr('id');
  if (id == "whatever") {
    ............
  } else if (id == "somethingelse") {
    ............
  }
 }
});
于 2012-09-18T03:54:18.560 に答える