Scrolling inner div on key down and up

前端 未结 5 1875
你的背包
你的背包 2021-02-05 20:37

I have build an autocomplete container which displays the first four results and the rest are hidden and can be seen when scrolling the inner div element which holds all the res

5条回答
  •  佛祖请我去吃肉
    2021-02-05 21:13

    There are several ways to implement it. and the exact solution for you need to consider your context.

    Anyway, one possible solution is to use in the container div 'position: relative' and in the inner div (which hold the content) use 'position: absolute' and 'top: 0px'. When user press on the up/down arrows you changing the top property accordingly.

    CSS:

    .container {
        position: relative;
        height: 50px;
        width: 200px;
        overflow: hidden;
        border: 1px solid blue;
    }
    
    .content {
        position: absolute;
        top: 0px;
    }
    

    JavaScript:

    function moveContent(px) {
        var top = $('.content').position().top;
        $(".content").css("top", top+px);
    }
    
    $(document).keydown(function(e){
        if (e.keyCode == 38) { 
           moveContent(-5);
        }
        if (e.keyCode == 40) { 
           moveContent(5);
        }
    });
    

    HTML:

    hello 1
    hello 2
    hello 3
    hello 4
    hello 5
    hello 6

    See my example in: http://jsfiddle.net/Kq2Qq/3/

提交回复
热议问题