jQuery动画Scrolltop无法正常工作

时间:2017-03-17 12:47:05

标签: javascript jquery html css

我尝试使用jquery在按钮单击时将页面滚动到特定div。即使我没有在js控制台中收到错误,页面也不会滚动到所需的div。我甚至尝试在&之前添加jquery js文件在标签之后但问题仍然存在。

检查代码:



$("#search_btn_home").click(function() {
  console.log("Inside existing click function of search");
  $('html,body').animate({
    scrollTop: $("#friendstoreline").offset().top
  }, 'slow');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-image: url('images/bluebackground.jpg'); background-repeat: repeat; min-height: 500px">
  <div id="search_btn_home">
    Click
  </div><br />
  <div id="friendstoreline"><strong>The Friend Store</strong></div><br />
</div>
&#13;
&#13;
&#13;

即使上述消息正在控制台中打印而没有错误,页面也不会滚动到所需的div。请帮助..

3 个答案:

答案 0 :(得分:1)

在添加标识为#search_btn_home

的按钮后,它正在工作

JSFIDDLE

$("#search_btn_home").click(function() {
  console.log("Inside existing click function of search");
  $('html,body').animate({
      scrollTop: $("#friendstoreline").offset().top
    },
    'slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="min-height:500px">
  <br />
  <div id="friendstoreline"><strong>The Friend Store</strong></div>
  <br />
</div>
<button id="search_btn_home">CLICK

</button>

答案 1 :(得分:0)

我试图在codepen中运行你的代码并且它有效。 也许你的视图没有溢出,所以页面无法滚动到所需的对象(因为它已经在页面上)。

我在代码中更改的内容包括缺少的按钮

<button id="search_btn_home">Scroll</button>

查看my codepen并检查它是否能解决您的问题。

答案 2 :(得分:0)

您可以使用以下内容:

<div id="menu"><button class="page-scroll" href="#friendstoreline"></button></div>
<div style="background-image: url('images/bluebackground.jpg');
background-repeat:repeat;min-height:500px">
<br />
<div id="friendstoreline"><strong>The Friend Store</strong></div>
<br />

相关问题