我正在创建代码,其中div将在下一个/上一个按钮上垂直无限滚动...我已经创建了它,但是其中存在一个小问题..当我单击上一个按钮时,div首先在上滚动单击,然后它向下滚动,下一个按钮也一样。.请有人帮助
var buttons = $('.next-prev');
$(buttons).each(function(){
$(this).click(function(){
var id = $(this).attr('id');
if(id=="next"){
$('#scroll-div').stop().animate({scrollTop:40},400,'swing',function(){
$(this).scrollTop(0).find('div:last').after($('div:first', this));
});
}
else {
$('#scroll-div').stop().animate({scrollTop:40},400,'swing',function(){
$(this).scrollTop(40).find(' div:first').before($(' div:last', this));
});
}
})
})
* {
box-sizing: border-box;
}
#scroll-div {
overflow: hidden;
width: 300px;
height: 250px;
background: green;
padding: 10px;
}
#scroll-div div {
display: block;
height: 30px;
padding: 10px 10px;
margin-bottom: 10px;
background: cyan;
}
.item:last-child {
margin-bottom: 0px;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button class="next-prev" id="next">
up
</button>
<button class="next-prev" id="prev">
down
</button>
</div>
<div id="scroll-div">
<div>div 1</div>
<div>div 2</div>
<div>div 3</div>
<div>div 4</div>
<div>div 5</div>
<div>div 6</div>
<div>div 7</div>
<div>div 8</div>
<div>div 9</div>
<div>div 10</div>
</div>
答案 0 :(得分:1)
var buttons = $('.next-prev');
$('#scroll-div').prepend($('#scroll-div').find('div:last-child')); // prepend last element
$('#scroll-div').scrollTop(40); // scroll div to position 40 so first (div 10) not visible
$(buttons).each(function(){
$(this).click(function(){
var id = $(this).attr('id');
if(id=="next"){
$('#scroll-div').append($('#scroll-div').find('div:first-child')); //do modification first
} else {
$('#scroll-div').prepend($('#scroll-div').find('div:last-child'));
}
$('#scroll-div').stop().animate({scrollTop:40},400,'swing'); // then scroll
})
})
* {
box-sizing: border-box;
}
#scroll-div {
overflow: hidden;
width: 300px;
height: 250px;
background: green;
padding: 10px;
}
#scroll-div div {
display: block;
height: 30px;
padding: 10px 10px;
margin-bottom: 10px;
background: cyan;
}
.item:last-child {
margin-bottom: 0px;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button class="next-prev" id="next">
up
</button>
<button class="next-prev" id="prev">
down
</button>
</div>
<div id="scroll-div">
<div>div 1</div>
<div>div 2</div>
<div>div 3</div>
<div>div 4</div>
<div>div 5</div>
<div>div 6</div>
<div>div 7</div>
<div>div 8</div>
<div>div 9</div>
<div>div 10</div>
</div>