首页 > 像这样的点击一个侧边选项,页面平缓过渡到目的位置是如何做到的?

像这样的点击一个侧边选项,页面平缓过渡到目的位置是如何做到的?

看了京东的页面,点击1、2、...nF,页面即可平缓的滚到目的位置,请问是如何实现的?


如楼上两位所说,的确使用了animation方法,该楼层组件定义在
http://misc.360buyimg.com/??jdf/1.0.0/unit/globalInit/2.0.0/globalInit.js,jdf/1.0.0/unit/localStorage/1.0.0/localStorage.js,jdf/1.0.0/unit/cookie/1.0.0/cookie.js,jdf/1.0.0/unit/price/1.0.0/price.js,jdf/1.0.0/ui/lazyload/1.0.0/lazyload.js,jdf/1.0.0/ui/switchable/1.0.0/switchable.js,jdf/1.0.0/ui/easing/1.0.0/easing.js,jdf/1.0.0/ui/fixable/1.0.0/fixable.js,jdf/1.0.0/ui/smartkey/1.0.0/smartkey.js,jdf/1.0.0/ui/elevator/1.0.0/elevator.js,product/home/1.0.0/widget/hotwords/hotwords.js,product/home/1.0.0/widget/elevator/elevator.js,product/home/1.0.0/widget/focus/focus.js,product/home/1.0.0/widget/lifeserv/lifeserv.js,product/home/1.0.0/js/patch.js,product/home/1.0.0/js/banner.js
jd使用了后端combo打包JS。在chrome Source面板中可以查看到,formatted之后在1700左右,而这个缓动效果是使用了自定义了运动函数,约在969行


使用jQuery的animate + scrollTop

$(document).animate({scrollTop:$("#7F").offset().top}, 1000);

document 可能在不同的浏览器里需要进行兼容处理


我利用原本錨點( anchor )的特性,把原本跳轉到錨點的預設行為給取消掉,改由 jQuery 來控制捲軸動畫,這樣做的好處是只要很簡單的新增 <a href="#錨點名稱"> <section id="錨點名稱"></section>,就可以實現添加更多區塊,不一定要 section ,其他元素也可以,例如 h1 div

例子

Codepen

實現

html

<div class="main">
  <div class="sidebar">
    <ul class="navigation">
      <li><a href="#1f">1F</a></li>
      <li><a href="#2f">2F</a></li>
      <li><a href="#3f">3F</a></li>
    </ul>
  </div>
  <div class="content">
    <section id="1f" class="floor 1f">
      <h1>1F</h1>
    </section>
    <section id="2f" class="floor 2f">
      <h1>2F</h1>
    </section>
    <section id="3f" class="floor 3f">
      <h1>3F</h1>
    </section>
  </div>
</div>

javascript

// 綁定導航列每個 a 的點擊事件
$('.navigation > li > a').click(function(e) {
  e.preventDefault() // 取消預設動作(直接跳轉到錨點)
  // 改由 jquery 的 animate 實現平滑移動到錨點
  $('html, body').animate({
      // 取得原先要移動至的元素,取得離上方距離,在 300ms 內完成捲軸動畫
      scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 300);
  })
})

每层楼和侧边栏的按钮对应起来,点击按钮时,计算楼层距离页面顶部的距离,这个距离就是要滚动的距离,然后使用动画库滚动页面就好了,如上面兄弟说的 jquery 的 animate

【热门文章】
【热门文章】