我可以在不编写函数的情况下使用 scrollTop 吗?

Can I use scrollTop without writing a function?

本文关键字:scrollTop 情况下 函数 我可以      更新时间:2023-09-26

我的jQuery遇到了一些问题,正在寻找一些解决方案来为我已经存在的slideDown函数添加一些东西。

对我来说非常有趣的是 2010 年的这个问题/答案 http://stackoverflow.com/questions/4034659/is-it-possible-to-animate-scrollop-with-jquery

这个问题的不同之处在于,我正在寻找一种解决方案,每次都scrollTop到不同的<a> anchor

在下面的示例中,<a href"#">应该移动到顶部。

这可能吗?

.HTML

<div class="next_btn" id="next_btn_show_step_3">
    <a href="#"><?php echo $lang ['next']; ?></a>
</div>
<article class="order_form_step_3" id="banner_step_3">
</article>

jQuery

$(document).ready(function(){
  $("#banner_step_3").hide();
  $("#next_btn_show_step_3").click(function(e){
    $("#banner_step_3").slideDown(500);
    e.preventDefault();
  });
});

你可以很容易地像这样改编这个答案:

$("html, body").animate({ scrollTop: Math.floor($('#yourElement').offset().top) + "px" });

jquery

$('.next_btn a').on('click', function(e) {//on link click
    var th = $(this);//get element
    th.parent().next('article').slideDown(500);//slide down
    $('html, body').animate({ scrollTop: th.offset().top }, 500);//scrollto link
    e.preventDefault();//prevent default
});