我正在构建一个动态表单/div,它在右下角有一个克隆按钮。单击它后,它应该克隆 .item:first
然后自动向下滚动以便隐藏最后一个 div。当您单击上一个或下一个按钮时,它应该滚动到我想要的确切 div。目前我的方法是使用具有固定 px
的 scrollTop
但它无效。因为我们有很多屏幕尺寸。我怎样才能做到这一点?谢谢
var template = $('#section .item:first').clone();
var sectionsCount = 1;
$('.new-div').click(function() {
$('html, body').animate({
scrollTop: '+=700'
}, 800);
});
$('body').on('click', '.new-div', function() {
sectionsCount++;
var section = template.clone().find('.item').each(function() {}).end()
.appendTo('#section');
return false;
});
$(".next").click(function(event) {
event.preventDefault();
$('html, body').animate({
scrollTop: '+=700'
}, 800);
});
$(".prev").click(function(event) {
event.preventDefault();
$('html, body').animate({
scrollTop: '-=700'
}, 800);
});
body {
background-color: lightgrey;
}
#section {
height: 100vh;
padding: 50px;
}
.item {
width: 500px;
background-color: white;
height: 100%;
margin: auto;
text-align: center;
padding: 20px;
margin-bottom: 100px;
}
.new-div {
position: fixed;
right: 20px;
bottom: 20px;
padding: 20px;
border-radius: 10px;
color: inherit;
font-family: helvetica;
text-decoration: none;
background: #eee;
}
.prev {
position: fixed;
right: 20px;
bottom: 180px;
padding: 20px;
border-radius: 10px;
color: inherit;
font-family: helvetica;
text-decoration: none;
background: #eee;
}
.next {
position: fixed;
right: 20px;
bottom: 100px;
padding: 20px;
border-radius: 10px;
color: inherit;
font-family: helvetica;
text-decoration: none;
background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section">
<div class="item">
<h1 class="head">Div</h1>
</div>
</div>
<a href="" class="new-div">New div</a>
<a href="" class="prev">prev</a>
<a href="" class="next">next</a>
最佳答案
您可以使用 topPos = element.offsetTop;
获取所需 DIV 的偏移量,然后滚动到其位置。有关 offsetTop 的更多信息,请访问此处在这里。
topPos = element.offsetTop;
$('html, body').animate({
scrollTop: topPos
}, 800);
代码可以这样使用。
J查询:
topPos = $($(".item")[0]).position().top;
$('html, body').animate({
scrollTop: topPos+"px"
}, 800);
关于javascript - 使用 jQuery 在单击时滚动到下一个或上一个 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51265358/