如何在scrollTop()函数中使用变量'+=' + itemHeight + 'px'
http://codepen.io/anon/pen/mVwOwy
var itemHeight = $(item).height(); // item height
//keyup
if (event.which == 38) {
$(box).stop().animate({scrollTop: '-=' + itemHeight + 'px'}, 100);
event.preventDefault();
console.log('-='+ itemHeight + 'px');
// if active item is first child
if (active.index() !== 0) {
$(active).removeClass('active').prev().addClass('active');
console.log('123');
}
}
答案 0 :(得分:1)
<强>编辑强>
你的代码很好,你只做了一件小事。
你在哪里使用&#34; - =&#34;在你的keydown上,这是你想要的逆转效果。我将其更改为&#34; + =&#34;它增加了当前值的高度,并且可以解决问题。以下代码是您所需要的:)
KEYUP
$(box).stop().animate({
scrollTop: '-=' + itemHeight
}, 100);
KEYDOWN
$(box).stop().animate({
scrollTop: '+=' + itemHeight
}, 100);
<强>段强>
$(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++;
});
});
&#13;
* {
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 */
&#13;
<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>
&#13;