Scrolling inner div on key down and up

前端 未结 5 1865
你的背包
你的背包 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 20:58

    You can update your script to find the relative position of the selected element and scroll to it:

    $(".someInput").on("keyup", function(e) {
       $(".wrapper").show(); 
        if (e.which == 40) {
            $('.element:not(:last-child).element-hover').removeClass('element-hover').next().addClass('element-hover');
        } else if (e.which == 38) {
            $('.element:not(:first-child).element-hover').removeClass('element-hover').prev().addClass('element-hover');    
        }
        //scroll to element:
        $(".wrapper .inner_div").scrollTop(0);//set to top
        $(".wrapper .inner_div").scrollTop($('.element-hover:first').offset().top-$(".wrapper .inner_div").height());//then set equal to the position of the selected element minus the height of scrolling div
    });
    

    http://jsfiddle.net/kMzR9/3/

提交回复
热议问题