我想创建一个滚动到 jquery
中多个元素位置的按钮。
假设我有这段代码:
<div class="container">
<div>This is div one.</div>
<div>This is div two.</div>
<div>This is div three.</div>
<div>This is div four.</div>
<div>This is div five.</div>
</div>
我可以在 jquery
中创建一个事件,如下所示:
$('button#divone').click(function(){
$('body').scrollTop(/*Element pos*/);
});
但是,这意味着我必须为每个 div 创建一个按钮,并为每个 div 创建一个 jquery
事件。
还有什么更好的办法吗?
最佳答案
试试这个:
$(document).ready(function(){
var scrolled = 1;
/*If you want it to start from the first div set the value to 0;*/
var elements = $('div.container').find('div').length;
/*Scroll Down button*/
$('button#scrollbtn_D').click(function(){
var pos = $('div.container div').eq(scrolled).offset().top;
$('html,body').animate({
scrollTop: pos},
'slow');
scrolled += 1;
if(scrolled>=elements){
$(this).hide();
}
$('button#scrollbtn_U').show();
});
/*Scroll Up button*/
$('button#scrollbtn_U').click(function(){
scrolled -= 2;
var pos = $('div.container div').eq(scrolled).offset().top;
$('html,body').animate({
scrollTop: pos},
'slow');
scrolled += 1;
if(scrolled==1){
$(this).hide();
}
$('button#scrollbtn_D').show();
});
$('button#scrollbtn_U').hide();
});
div.container{
width: 300px;
height: auto;
position: relative;
padding: 10px;
border: 1px solid rgba(0,0,0,0.1);
}
div.container div{
width: 100%;
height: 300px;
text-align: center;
}
button#scrollbtn_D{
width:50px;
height:50px;
position: fixed;
top: 8px;
left:340px;
cursor: pointer;
}
button#scrollbtn_U{
width:50px;
height:50px;
position: fixed;
top: 8px;
left:395px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div>This is div one.</div>
<div>This is div two.</div>
<div>This is div three.</div>
<div>This is div four.</div>
<div>This is div five.</div>
</div>
<button id="scrollbtn_D">Down</button>
<button id="scrollbtn_U">Up</button>
关于jquery - 滚动按钮滚动到多个元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51572562/