简体   繁体   中英

Set top of menu at middle of ul element when scrolling with arrow keys

I have a drop down menu that opens when you click on the input field and activates a blue background on the selected item when clicking the up or down arrow keys. It also keeps the selected item at the top to prevent the selection from disappearing.

What I would like to do is fix the 'top' to the middle of the menu after the user clicks the down arrow key once so that the selection sits in the middle as the user scrolls up or down.

I've tried to play around with the scrollTop() method by dividing it in half, but I can't seem to make this work.

jsfiddle

 $( document ).ready(function() { var $menu = $('#menu'); var $input = $('#maininput'); $menu.hide(); $input.focus(function () { $menu.show(); }); $input.blur(function () { $menu.hide(); }); $input.on('keyup', function (e) { if (e.keyCode === 40 ) { // down e.preventDefault(); var selected = $(".selected"); var $list = $("li.list"); var index = $list.index(selected); $list.removeClass("selected"); $list.eq(index + 1).addClass("selected"); $(".main ul").scrollTop($('li').index($(".selected")) * $('.main li').height()); } if (e.keyCode === 38) { // up e.preventDefault(); var selected = $(".selected"); var $list = $("li.list"); var index = $list.index(selected); $list.removeClass("selected"); $list.eq(index - 1).addClass("selected"); $(".main ul").scrollTop($('li').index($(".selected")) * $('.main li').height()); } }) }); 
 li { list-style: none; } ul { padding: 0px; margin: 0px; background-color: #eee; width: 130px; height: 120px; overflow: auto; overflow-x:hidden; border-spacing: 10px; } .list { /* padding-top: 5px; padding-bottom: 5px; */ padding-left: 10px; height: 40px; line-height: 2.1em; } #maininput { padding: 10px; } .selected { background-color: #d2d2d2; border-radius: 4px; width: 220px; background-color: #0096d6; border-radius: 4px; width: 100%; color: #ffffff; } 
 <html> <body> <input id="maininput" /> <div class="main"> <ul id="menu"> <li class="list">one</li> <li class="list">two</li> <li class="list">three</li> <li class="list">four</li> <li class="list">five</li> <li class="list">six</li> <li class="list">seven</li> <li class="list">eight</li> <li class="list">nine</li> <li class="list">ten</li> </ul> </div> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> </body> </html> 

Help is appreciated. Thanks.

Edit this line in javascript(for both up and down):

$(".main ul").scrollTop($('li').index($(".selected")) * $('.main li').height());

with this line:

$(".main ul").scrollTop(($('li').index($(".selected"))-1) * $('.main li').height());

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