简体   繁体   中英

How to navigate between HTML element using keyboard arrow keys

I want my web page to allow navigation between blocks of text using the left and right arrow keys on a keyboard. I assume this would require Jquery.

I have literally read a dozen posts on Stackoverflow that seemingly address this question without really answering it...so please don't close this as a duplicate question

UPDATE: I simply want to scroll between articles (like blog posts) using the arrow keys. All I want is to scroll the page to the next divider.

Here's a JS Fiddle I made for you: http://jsfiddle.net/3NAwz/

This code shows div tags that contain text, floating to the left within a wrapper. That is then contained in another wrapper that is smaller than the overall text (one section of it).

jQuery is then used to scroll along the content using the arrow keys. The .not(":animated") part stops it from animating if it is already animating. Using this just makes it nicer without a horrible long queue after some 5 year old decides to be very impatient.

HTML

<div class="wrapper">
    <div class="inner">
        <div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas aliquam erat vitae nibh convallis quis luctus turpis dignissim. Suspendisse imperdiet interdum consequat. Curabitur erat nisl, gravida et aliquet vitae, faucibus vitae lacus.</div>
        <div class="text">Donec dignissim lorem eu augue tincidunt facilisis. Etiam leo purus, tristique eu tempus gravida, auctor sit amet velit. Quisque mattis, libero ut pharetra luctus, tellus justo viverra elit, sodales scelerisque ipsum magna vel felis.</div>
        <div class="text">Pellentesque ligula mauris, volutpat id molestie posuere, fermentum eu lacus. Donec quis metus nisi, et accumsan massa. Morbi eget augue eget lorem semper cursus sit amet non tortor. Aliquam tempor rhoncus odio sit amet fermentum.</div>
    </div>
</div>​

CSS

.wrapper {
    width:340px;
    overflow:hidden;
    border:1px #000 solid;
}
.inner {
    width:1020px;
}
.text {
    float:left;
    width:300px;
    padding:20px;
    font-size:14px;
    font-weight:bold;
    font-family:Arial;
}

jQuery

$(document).ready(function() {
    $(document).keyup(function(event) {
        var key = event.which;
        if(key == 37) { // Left arrow key
            $(".wrapper").not(":animated").animate({ scrollLeft: "-=340px" }, 500);
        }
        if(key == 39) { //Right arrow key
            $(".wrapper").not(":animated").animate({ scrollLeft: "+=340px" }, 500);
        }
    });
});​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM