javascript - 使用 jQuery 在单击时滚动到下一个或上一个 DIV

标签 javascript jquery html

我正在构建一个动态表单/div,它在右下角有一个克隆按钮。单击它后,它应该克隆 .item:first 然后自动向下滚动以便隐藏最后一个 div。当您单击上一个或下一个按钮时,它应该滚动到我想要的确切 div。目前我的方法是使用具有固定 pxscrollTop 但它无效。因为我们有很多屏幕尺寸。我怎样才能做到这一点?谢谢

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/

相关文章:

javascript - 使用 Navigate/Routes 调试路线

Javascript 函数对象,this 关键字指向错误的对象

javascript - 如何将现有的非 React-Native-Component JS 导入/需要到 React Native 组件

jquery - Fancybox 删除滚动,移动页面

jquery - 您如何在轻松的同时使 Logo 滑入和滑出页面?

asp.net - 更改 ASP.NET XHTML 呈现模式

javascript - 如何删除 nicEdit 文本编辑器中的上传按钮

javascript - 在 JS 中向突出显示的文本添加标签不起作用

javascript - 正则表达式去除包装 DIV 标签

javascript - 使用 javascript/jquery 将随机 css 类添加到随机元素