JS点击跳到指定div的位置

1.给链接a加个#的方式来实现跳转(锚点方法)

<div id="container">
    <a href="#div1">div1</a>
    <a href="#div2">div2</a>
    <a href="#div3">div3</a>
</div>
  <div id="div1">div1</div>
  <div id="div2">div2</div>
  <div id="div3">div3</div>

 

2.用animate属性,当点击锚点后,页面滚动到相应的DIV

<div id="container">
     <p id="p1">div1</p>
     <p id="p2">div2</p>
     <p id="p3">div3</p>
</div>
  <div id="div1">div1</div>
  <div id="div2">div2</div>
  <div id="div3">div3</div>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
$(document).ready(function() {
  $("#p1").click(function() {
    $("html, body").animate({
      scrollTop: $("#div1").offset().top }, {duration: 500,easing: "swing"});
    return false;
  });
  $("#p2").click(function() {
    $("html, body").animate({
      scrollTop: $("#div2").offset().top }, {duration: 500,easing: "swing"});
    return false;
  });
  $("#p3").click(function() {
    $("html, body").animate({
      scrollTop: $("#div3").offset().top }, {duration: 500,easing: "swing"});
    return false;
  });
});

 

posted @ 2021-04-16 19:57  十三月凉  阅读(1726)  评论(0编辑  收藏  举报
/* 看板娘 */