如何在 jQuery 中正确滚动顶部到 div?

问题描述 投票:0回答:2

我有:

<button class="contactButton">XYZ</button>

当用户按下此按钮时,我希望我的页面向下滚动到特定的 div。

我试过这个:

$(".contactButton").click(function () {
    $("html,body").animate({
    scrollTop: $(".specificDivClass").offset().top
    }, 1100);
});
jquery html scroll
2个回答
3
投票

这里有一个解决方案https://jsfiddle.net/psfLbo1n/

$(".contactButton").click(function () {
    $("html,body").animate({
    	scrollTop: $(".specificDivClass").offset().top
    }, 1100);
});
.div1{
  height: 700px;
  width: 100%;
  background: red;
}

.specificDivClass{
  height: 1000px;
  width: 100%;
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="contactButton">XYZ</button>

<div class="div1">

</div>

<div class="specificDivClass">

</div>


1
投票

最有可能的问题是类名拼写错误和/或未将 JavaScript 包含到 HTML 中。您可以尝试使用 ID 而不是 class 来选择要滚动到的元素。

© www.soinside.com 2019 - 2024. All rights reserved.