редактирует
Ваш код был хорошим, ты только что сделал один крошечный вещь неправильно. Вы, где используете «- =» на вашем keydown, а это был обратный эффект, который вы хотели. Я изменил его на «+ =», который добавляет высоту к текущему значению, и это сделало трюк. Приведенный ниже код является то, что вам нужно :)
KeyUp
$(box).stop().animate({
scrollTop: '-=' + itemHeight
}, 100);
KeyDown
$(box).stop().animate({
scrollTop: '+=' + itemHeight
}, 100);
Snippet
$(document).ready(function() {
//item
var box = $('.sel-wrapper');
var item = $('.sel-wrapper li');
var active = $('.sel-wrapper li.active');
var itemHeight = $(item).outerHeight(); // item height
console.log(itemHeight);
$(item).on('click', function() {
$(item).removeClass('active');
$(this).addClass('active');
});
//
var counter = 0;
$(document).keydown(function(event) {
var box = $('.sel-wrapper');
var item = $('.sel-wrapper li');
var active = $('.sel-wrapper li.active');
//keyup
if (event.which == 38) {
$(box).stop().animate({
scrollTop: '-=' + itemHeight
}, 100);
event.preventDefault();
// if active item is first child
if (active.index() !== 0) {
$(active).removeClass('active').prev().addClass('active');
console.log('123');
}
}
//keydown
if (event.which == 40) {
$(box).stop().animate({
scrollTop: '+=' + itemHeight
}, 100);
event.preventDefault();
// if active item is last child
if (active.index() !== item.length - 1) {
$(active).removeClass('active').next().addClass('active');
}
}
counter++;
});
});
* {
box-sizing: border-box;
font-family: sans-serif;
}
body {
margin: 0;
padding: 0;
}
.row {
width: 100%;
}
.sel-wrapper {
padding: 10px 0;
overflow-y: auto;
margin: 20px auto;
width: 200px;
height: 100px;
border: 1px solid black;
}
.sel-wrapper ul {
list-style: none;
padding: 0;
margin: 0;
}
.sel-wrapper li {
padding: 4px 10px;
cursor: pointer;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
.sel-wrapper li:hover {
background: rgba(60, 63, 65, 0.49);
}
.sel-wrapper li.active {
background: #1a8bff;
color: #fff;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
/*# sourceMappingURL=style.css.map */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sel-wrapper">
<ul>
<li class="active">123</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
Удалить '+' px'' pixel - это единица по умолчанию, так или иначе –
все еще не работает. –
Вам необходимо предоставить MCVE, реплицирующее вашу проблему. 'все еще не работает' на самом деле не помогает ... –